// Auth screens — alle Store-Calls sind async
const LoginScreen = ({ onSuccess, onRegister }) => {
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault(); setErr('');
    if (!email || !pw) { setErr('Bitte alle Felder ausfüllen.'); return; }
    setLoading(true);
    const res = await Store.login(email, pw);
    setLoading(false);
    if (res.error) { setErr(res.error); return; }
    onSuccess(res.session);
  };

  return (
    <div className="auth-shell"><div className="auth-card">
      <div className="auth-brand"><Icon name="logo-cross" size={28}/><div style={{fontSize:20,fontWeight:600,letterSpacing:'-0.02em'}}>ImmoHub<sup style={{fontSize:11,fontWeight:400}}>Schweiz</sup></div></div>
      <h2 className="auth-title">Anmelden</h2>
      <p className="auth-sub">Willkommen zurück. Melden Sie sich mit Ihrer E-Mail und Ihrem Passwort an.</p>
      <form onSubmit={submit} className="auth-form">
        <div className="field"><label>E-Mail</label><input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="name@firma.ch" autoFocus/></div>
        <div className="field"><label>Passwort</label><input type="password" value={pw} onChange={e=>setPw(e.target.value)} placeholder="••••••••"/></div>
        {err && <div className="auth-error">{err}</div>}
        <button type="submit" className="btn btn-primary btn-full" disabled={loading}>{loading?'Wird angemeldet…':'Anmelden'}</button>
      </form>
      <div className="auth-footer">Noch kein Konto? <button className="link-btn" onClick={onRegister}>Jetzt registrieren</button></div>
    </div></div>
  );
};

const RegisterScreen = ({ onSuccess, onLogin }) => {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({name:'',email:'',pw:'',pw2:'',company:''});
  const [addedProps, setAddedProps] = React.useState([]);
  const [newProp, setNewProp] = React.useState({street:'',city:'',plz:'',units:'',built:''});
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [session, setSession] = React.useState(null);

  const upd = (k,v) => setData(d=>({...d,[k]:v}));
  const updP = (k,v) => setNewProp(p=>({...p,[k]:v}));

  const step1 = async (e) => {
    e.preventDefault(); setErr('');
    if (!data.name||!data.email||!data.pw||!data.company){setErr('Bitte alle Felder ausfüllen.');return;}
    if (data.pw!==data.pw2){setErr('Passwörter stimmen nicht überein.');return;}
    if (data.pw.length<6){setErr('Passwort muss mindestens 6 Zeichen lang sein.');return;}
    setLoading(true);
    const res = await Store.register({name:data.name,email:data.email,pw:data.pw,company:data.company});
    setLoading(false);
    if (res.error){setErr(res.error);return;}
    setSession(res.session); setStep(2);
  };

  const addProp = async () => {
    if (!newProp.street||!newProp.city||loading) return;
    setLoading(true);
    try { const p = await Store.addProperty(null, newProp); setAddedProps(a=>[...a,p]); } catch {}
    setLoading(false);
    setNewProp({street:'',city:'',plz:'',units:'',built:''});
  };

  if (step===1) return (
    <div className="auth-shell"><div className="auth-card">
      <div className="auth-brand"><Icon name="logo-cross" size={28}/><div style={{fontSize:20,fontWeight:600,letterSpacing:'-0.02em'}}>ImmoHub<sup style={{fontSize:11,fontWeight:400}}>Schweiz</sup></div></div>
      <div className="auth-steps"><span className="step active">1 Konto</span><span className="step-sep">›</span><span className="step">2 Liegenschaften</span><span className="step-sep">›</span><span className="step">3 Fertig</span></div>
      <h2 className="auth-title">Konto erstellen</h2>
      <p className="auth-sub">Verwalten Sie Ihre Liegenschaften digital. Kostenlos starten.</p>
      <form onSubmit={step1} className="auth-form">
        <div className="field-row">
          <div className="field"><label>Ihr Name</label><input type="text" value={data.name} onChange={e=>upd('name',e.target.value)} placeholder="Vorname Nachname" autoFocus/></div>
          <div className="field"><label>Firmenname</label><input type="text" value={data.company} onChange={e=>upd('company',e.target.value)} placeholder="Müller Immobilien AG"/></div>
        </div>
        <div className="field"><label>E-Mail</label><input type="email" value={data.email} onChange={e=>upd('email',e.target.value)} placeholder="name@firma.ch"/></div>
        <div className="field-row">
          <div className="field"><label>Passwort</label><input type="password" value={data.pw} onChange={e=>upd('pw',e.target.value)} placeholder="Mind. 6 Zeichen"/></div>
          <div className="field"><label>Wiederholen</label><input type="password" value={data.pw2} onChange={e=>upd('pw2',e.target.value)} placeholder="••••••••"/></div>
        </div>
        {err && <div className="auth-error">{err}</div>}
        <button type="submit" className="btn btn-primary btn-full" disabled={loading}>{loading?'Wird angelegt…':'Weiter →'}</button>
      </form>
      <div className="auth-footer">Bereits registriert? <button className="link-btn" onClick={onLogin}>Anmelden</button></div>
    </div></div>
  );

  return (
    <div className="auth-shell"><div className="auth-card auth-card-wide">
      <div className="auth-brand"><Icon name="logo-cross" size={28}/><div style={{fontSize:20,fontWeight:600,letterSpacing:'-0.02em'}}>ImmoHub<sup style={{fontSize:11,fontWeight:400}}>Schweiz</sup></div></div>
      <div className="auth-steps"><span className="step done">1 Konto ✓</span><span className="step-sep">›</span><span className="step active">2 Liegenschaften</span><span className="step-sep">›</span><span className="step">3 Fertig</span></div>
      <h2 className="auth-title">Liegenschaften hinzufügen</h2>
      <p className="auth-sub">Fügen Sie Ihre Liegenschaften hinzu. Sie können später weitere ergänzen.</p>
      {addedProps.length>0 && <div className="prop-list">{addedProps.map((p,i)=>(
        <div key={i} className="prop-item"><Icon name="building" size={14}/><div><div style={{fontWeight:500,fontSize:13}}>{p.street}</div><div className="text-xs text-muted">{p.plz} {p.city} · {p.units} Einheiten</div></div><Badge tone="ok" dot={false}>Gespeichert</Badge></div>
      ))}</div>}
      <div className="prop-add-form">
        <div className="field-row">
          <div className="field" style={{flex:2}}><label>Strasse und Hausnummer</label><input type="text" value={newProp.street} onChange={e=>updP('street',e.target.value)} placeholder="Rämistrasse 42"/></div>
          <div className="field"><label>PLZ</label><input type="text" value={newProp.plz} onChange={e=>updP('plz',e.target.value)} placeholder="8001" maxLength={4}/></div>
          <div className="field"><label>Ort</label><input type="text" value={newProp.city} onChange={e=>updP('city',e.target.value)} placeholder="Zürich"/></div>
        </div>
        <div className="field-row">
          <div className="field"><label>Anzahl Einheiten</label><input type="number" value={newProp.units} onChange={e=>updP('units',e.target.value)} placeholder="12" min={1}/></div>
          <div className="field"><label>Baujahr</label><input type="text" value={newProp.built} onChange={e=>updP('built',e.target.value)} placeholder="1962"/></div>
          <div className="field" style={{display:'flex',alignItems:'flex-end'}}>
            <button className="btn btn-secondary btn-full" onClick={addProp} disabled={!newProp.street||!newProp.city||loading} type="button">{loading?'…':<><Icon name="plus" size={14}/> Hinzufügen</>}</button>
          </div>
        </div>
      </div>
      <div className="flex gap-8 mt-16">
        <button className="btn btn-ghost" onClick={()=>onSuccess(session)} type="button">Überspringen</button>
        <button className="btn btn-primary btn-full" onClick={()=>onSuccess(session)} type="button">
          {addedProps.length>0?`${addedProps.length} Liegenschaft${addedProps.length>1?'en':''} gespeichert → Weiter`:'Weiter →'}
        </button>
      </div>
    </div></div>
  );
};

const AcceptInviteScreen = ({ code, onSuccess }) => {
  const [invite, setInvite] = React.useState(null);
  const [notFound, setNotFound] = React.useState(false);
  const [name, setName] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    Store.getInvite(code).then(inv => { if (!inv){setNotFound(true);return;} setInvite(inv); setName(inv.name||''); });
  }, [code]);

  const submit = async (e) => {
    e.preventDefault(); setErr('');
    if (!name||!pw){setErr('Bitte alle Felder ausfüllen.');return;}
    if (pw!==pw2){setErr('Passwörter stimmen nicht überein.');return;}
    if (pw.length<6){setErr('Passwort muss mindestens 6 Zeichen lang sein.');return;}
    setLoading(true);
    const res = await Store.acceptInvite(code, {name, pw});
    setLoading(false);
    if (res.error){setErr(res.error);return;}
    onSuccess(res.session);
  };

  const roleLabel = {verwaltung:'Verwaltung',mieter:'Mieter',hauswart:'Hauswart'};

  if (notFound) return (
    <div className="auth-shell"><div className="auth-card">
      <div className="auth-brand"><Icon name="logo-cross" size={28}/><div style={{fontSize:20,fontWeight:600}}>ImmoHub<sup style={{fontSize:11}}>Schweiz</sup></div></div>
      <h2 className="auth-title">Einladung nicht gefunden</h2>
      <p className="auth-sub">Dieser Einladungslink ist ungültig oder wurde bereits verwendet.</p>
    </div></div>
  );

  if (!invite) return (
    <div className="auth-shell"><div className="auth-card" style={{textAlign:'center',padding:48}}>
      <div className="text-muted" style={{fontSize:13}}>Einladung wird geprüft…</div>
    </div></div>
  );

  return (
    <div className="auth-shell"><div className="auth-card">
      <div className="auth-brand"><Icon name="logo-cross" size={28}/><div style={{fontSize:20,fontWeight:600}}>ImmoHub<sup style={{fontSize:11}}>Schweiz</sup></div></div>
      <div className="invite-info">
        <div className="invite-badge"><Icon name="users" size={16}/><span>Einladung als <strong>{roleLabel[invite.role]||invite.role}</strong></span></div>
        {invite.org_name && <div className="text-xs text-muted mt-4">{invite.org_name}</div>}
        {invite.unit && <div className="text-xs font-mono mt-4">Einheit: {invite.unit}</div>}
      </div>
      <h2 className="auth-title">Konto aktivieren</h2>
      <p className="auth-sub">Einladung für <strong>{invite.email}</strong>. Wählen Sie Ihren Namen und ein Passwort.</p>
      <form onSubmit={submit} className="auth-form">
        <div className="field"><label>Ihr Name</label><input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="Vorname Nachname" autoFocus/></div>
        <div className="field-row">
          <div className="field"><label>Passwort</label><input type="password" value={pw} onChange={e=>setPw(e.target.value)} placeholder="Mind. 6 Zeichen"/></div>
          <div className="field"><label>Wiederholen</label><input type="password" value={pw2} onChange={e=>setPw2(e.target.value)} placeholder="••••••••"/></div>
        </div>
        {err && <div className="auth-error">{err}</div>}
        <button type="submit" className="btn btn-primary btn-full" disabled={loading}>{loading?'Wird aktiviert…':'Konto aktivieren & anmelden'}</button>
      </form>
    </div></div>
  );
};

Object.assign(window, { LoginScreen, RegisterScreen, AcceptInviteScreen });
