/* ═══════════════════════════════════════════════════════════════
   bezirk.live — Auth Screen
   Login / Signup via Supabase (Email + Password, Magic Link option)
   ═══════════════════════════════════════════════════════════════ */

function AuthScreen({ onAuthSuccess }){
  const [mode, setMode] = useState('welcome');     // welcome | signin | signup | magic | sent
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const [agbAccepted, setAgbAccepted] = useState(false);

  async function doSignUp(){
    if (!email || !password || !name){ setErr('Bitte alle Felder ausfüllen.'); return; }
    if (password.length < 6){ setErr('Passwort mindestens 6 Zeichen.'); return; }
    if (!agbAccepted){ setErr('Bitte AGB & Datenschutz akzeptieren, um fortzufahren.'); return; }
    setLoading(true); setErr('');
    try {
      const { data, error } = await window.BL.signUp(email, password, {
        name,
        handle: name.toLowerCase().replace(/\s+/g,'.'),
        agb_accepted_at: new Date().toISOString(),
      });
      if (error) throw error;
      if (data.session){ onAuthSuccess(data.user); }
      else { setMode('sent'); } // email confirmation required
    } catch(e){ setErr(e.message || 'Registrierung fehlgeschlagen.'); }
    setLoading(false);
  }

  async function doSignIn(){
    if (!email || !password){ setErr('Email und Passwort eingeben.'); return; }
    setLoading(true); setErr('');
    try {
      const { data, error } = await window.BL.signIn(email, password);
      if (error) throw error;
      onAuthSuccess(data.user);
    } catch(e){ setErr(e.message || 'Login fehlgeschlagen.'); }
    setLoading(false);
  }

  async function doMagicLink(){
    if (!email){ setErr('Email eingeben.'); return; }
    setLoading(true); setErr('');
    try {
      const { error } = await window.BL.signInMagic(email);
      if (error) throw error;
      setMode('sent');
    } catch(e){ setErr(e.message || 'Magic Link fehlgeschlagen.'); }
    setLoading(false);
  }

  // ─── WELCOME (with invite detection) ─────────────────────
  if (mode === 'welcome'){
    const invite = (typeof window.parseInviteOrt === 'function') ? window.parseInviteOrt() : null;

    return (
      <div style={S.bg}>
        <div style={S.hero}>
          <div style={S.logo}>b.</div>

          {invite ? (
            <>
              {/* Invite Pill */}
              <div style={{
                display:'inline-flex', alignItems:'center', gap:7, padding:'5px 11px',
                background:T.greenL, color:T.green, borderRadius:18, marginBottom:16,
                fontSize:11, fontWeight:800, letterSpacing:'.5px', alignSelf:'flex-start',
              }}>
                <span style={{width:6, height:6, borderRadius:'50%', background:T.green, animation:'pulse 1.6s ease-in-out infinite'}}></span>
                EINLADUNG AUS DEINER NACHBARSCHAFT
              </div>

              <div style={{fontFamily:'Fraunces,serif', fontSize:42, fontWeight:700, color:T.text, letterSpacing:'-1.3px', lineHeight:1.05, marginBottom:6}}>
                Willkommen in
              </div>
              <div style={{fontFamily:'Fraunces,serif', fontSize:42, fontWeight:700, color:T.green, letterSpacing:'-1.3px', lineHeight:1.05, marginBottom:18}}>
                {invite.name}.
              </div>

              <div style={{fontSize:15, color:T.sec, fontWeight:500, lineHeight:1.5, marginBottom:24, textWrap:'pretty'}}>
                Dein:e Nachbar:in hat dich auf <strong style={{color:T.text}}>bezirk.live</strong> eingeladen — den digitalen Dorfplatz für {invite.name}.<br/><br/>
                Hier findest du Hilfe von nebenan, lokale Empfehlungen und alles, was deinen Ort bewegt.
              </div>

              <div style={{padding:'12px 14px', background:'#fff', borderRadius:12, border:`1px solid ${T.bdr}`, fontSize:12.5, color:T.sec, fontWeight:500, lineHeight:1.45, marginBottom:8}}>
                <strong style={{color:T.text}}>✓ Was dich erwartet:</strong><br/>
                💬 Diskussionen in deinem Ort<br/>
                🤝 Hilfe von Nachbar:innen<br/>
                📦 Tauschen, verleihen, verschenken<br/>
                ⚡ Lokale Angebote & Deals
              </div>
            </>
          ) : (
            <>
              <div style={{fontFamily:'Fraunces,serif', fontSize:44, fontWeight:700, color:T.text, letterSpacing:'-1.5px', lineHeight:1.05, marginBottom:14}}>
                Hallo<br/>Nachbar:in.
              </div>
              <div style={{fontSize:16, color:T.sec, fontWeight:500, lineHeight:1.5, marginBottom:36, textWrap:'pretty'}}>
                Dein Bezirk — Hilfe, Tausch, Events, lokale Deals. Schnell, ehrlich, von nebenan.
              </div>
            </>
          )}
        </div>
        <div style={{padding:'0 24px 32px', display:'flex', flexDirection:'column', gap:10}}>
          <button style={S.btnPrimary} onClick={()=>setMode('signup')}>{invite ? `Konto erstellen für ${invite.name}` : 'Konto erstellen'}</button>
          <button style={S.btnGhost} onClick={()=>setMode('signin')}>Ich habe schon ein Konto</button>
          <div style={{textAlign:'center', fontSize:11, color:T.muted, marginTop:14, lineHeight:1.5}}>
            Mit der Registrierung akzeptierst du die<br/>Nutzungsbedingungen und Datenschutz­erklärung.
          </div>
        </div>
        <style>{`@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.5;transform:scale(.7)}}`}</style>
      </div>
    );
  }

  // ─── EMAIL SENT ──────────────────────────────────────────────
  if (mode === 'sent'){
    return (
      <div style={S.bg}>
        <div style={{...S.hero, justifyContent:'center', alignItems:'center', textAlign:'center'}}>
          <div style={{fontSize:64, marginBottom:18}}>📬</div>
          <div style={{fontFamily:'Fraunces,serif', fontSize:30, fontWeight:700, color:T.text, letterSpacing:'-.8px', marginBottom:12}}>
            Email gesendet
          </div>
          <div style={{fontSize:15, color:T.sec, fontWeight:500, lineHeight:1.5, maxWidth:300, marginBottom:30}}>
            Wir haben dir einen Link an<br/><strong style={{color:T.text}}>{email}</strong> geschickt. Klick darauf, um dich anzumelden.
          </div>
          <button style={{...S.btnGhost, width:'auto', padding:'10px 22px'}} onClick={()=>setMode('welcome')}>Zurück</button>
        </div>
      </div>
    );
  }

  // ─── SIGNIN / SIGNUP / MAGIC ────────────────────────────────
  const isSignup = mode === 'signup';
  const isMagic = mode === 'magic';
  return (
    <div style={S.bg}>
      <div style={{padding:'24px 22px 16px', display:'flex', alignItems:'center', gap:14}}>
        <button onClick={()=>setMode('welcome')} style={{background:'none', border:'none', fontSize:22, cursor:'pointer', color:T.text, padding:0}}>←</button>
        <div style={{fontFamily:'Fraunces,serif', fontSize:22, fontWeight:700, color:T.text, letterSpacing:'-.4px'}}>
          {isSignup ? 'Konto erstellen' : isMagic ? 'Magic Link' : 'Anmelden'}
        </div>
      </div>

      <div style={{flex:1, padding:'12px 24px', display:'flex', flexDirection:'column', gap:14, overflowY:'auto'}}>
        {isSignup && (
          <div>
            <div style={S.label}>Dein Name</div>
            <input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="z. B. Anna Müller" style={S.input} autoFocus/>
          </div>
        )}

        <div>
          <div style={S.label}>Email</div>
          <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="du@beispiel.at" style={S.input} autoFocus={!isSignup}/>
        </div>

        {!isMagic && (
          <div>
            <div style={S.label}>Passwort</div>
            <input type="password" value={password} onChange={e=>setPassword(e.target.value)} placeholder={isSignup?'Mind. 6 Zeichen':'••••••••'} style={S.input}/>
          </div>
        )}

        {err && <div style={{padding:'10px 12px', background:T.redL, color:T.red, borderRadius:10, fontSize:12.5, fontWeight:600, lineHeight:1.4}}>⚠ {err}</div>}

        {isSignup && (
          <label style={{display:'flex', gap:10, alignItems:'flex-start', padding:'12px 14px', background:'#fff', border:`1.5px solid ${agbAccepted?T.green:T.bdr}`, borderRadius:11, cursor:'pointer', marginTop:6}}>
            <input
              type="checkbox"
              checked={agbAccepted}
              onChange={e=>setAgbAccepted(e.target.checked)}
              style={{marginTop:2, width:18, height:18, accentColor:T.green, cursor:'pointer', flexShrink:0}}
            />
            <span style={{fontSize:12.5, color:T.sec, fontWeight:500, lineHeight:1.5}}>
              Ich akzeptiere die <a href="/agb.html" target="_blank" rel="noopener" style={{color:T.green, fontWeight:700, textDecoration:'underline'}}>Nutzungs­bedingungen</a> und die <a href="/datenschutz.html" target="_blank" rel="noopener" style={{color:T.green, fontWeight:700, textDecoration:'underline'}}>Datenschutz­erklärung</a> von bezirklive.at.
            </span>
          </label>
        )}

        <button
          style={{...S.btnPrimary, marginTop:8, opacity:loading?.6:1}}
          disabled={loading}
          onClick={isSignup ? doSignUp : (isMagic ? doMagicLink : doSignIn)}
        >
          {loading ? 'Moment…' : isSignup ? 'Registrieren' : isMagic ? 'Link senden' : 'Anmelden'}
        </button>

        {!isMagic && (
          <button style={{...S.btnGhost, marginTop:0}} onClick={()=>{setMode('magic'); setErr('');}}>
            ✉ Login per Email-Link (ohne Passwort)
          </button>
        )}

        <div style={{textAlign:'center', fontSize:13, color:T.sec, fontWeight:500, marginTop:8}}>
          {isSignup
            ? <>Schon ein Konto? <a onClick={()=>{setMode('signin'); setErr('');}} style={{color:T.green, fontWeight:700, cursor:'pointer'}}>Anmelden</a></>
            : <>Noch kein Konto? <a onClick={()=>{setMode('signup'); setErr('');}} style={{color:T.green, fontWeight:700, cursor:'pointer'}}>Konto erstellen</a></>
          }
        </div>
      </div>
    </div>
  );
}

// ─── STYLES ─────────────────────────────────────────────────────
const S = {
  bg:    { height:'100%', display:'flex', flexDirection:'column', background:T.bg, position:'relative', overflow:'hidden' },
  hero:  { flex:1, padding:'80px 28px 24px', display:'flex', flexDirection:'column', justifyContent:'flex-end' },
  logo:  {
    width:64, height:64, borderRadius:18, background:`linear-gradient(135deg, ${T.green}, #166435)`,
    display:'flex', alignItems:'center', justifyContent:'center', color:'#fff',
    fontFamily:'Fraunces,serif', fontWeight:700, fontSize:30, marginBottom:30,
    boxShadow:'0 10px 28px rgba(10,74,36,.3)',
  },
  label: { fontSize:12, fontWeight:700, color:T.sec, marginBottom:6, letterSpacing:'.2px', textTransform:'uppercase' },
  input: {
    width:'100%', padding:'14px 16px', fontSize:15, fontFamily:'inherit', fontWeight:500,
    background:'#fff', border:`1.5px solid ${T.bdr}`, borderRadius:12, color:T.text,
    outline:'none', transition:'border .15s',
  },
  btnPrimary: {
    width:'100%', padding:'15px 20px', fontSize:15, fontWeight:700, fontFamily:'inherit',
    background:T.green, color:'#fff', border:'none', borderRadius:14, cursor:'pointer',
    boxShadow:'0 6px 18px rgba(10,74,36,.25)',
  },
  btnGhost: {
    width:'100%', padding:'13px 20px', fontSize:14, fontWeight:600, fontFamily:'inherit',
    background:'transparent', color:T.text, border:`1.5px solid ${T.bdr}`, borderRadius:14, cursor:'pointer',
  },
};

Object.assign(window, { AuthScreen });
