// auth.jsx – Login und Firebase-Verbindung

const { useState: useAuthState } = React;

// ─── Login Screen ─────────────────────────────────────────────────
function AuthScreen({ onAuth }) {
  const [pwd, setPwd] = useAuthState("");
  const [err, setErr] = useAuthState(false);
  const PASS = "#Gem7STA";

  const check = () => {
    if (pwd === PASS) {
      sessionStorage.setItem("auth_v1", "1");
      onAuth();
    } else {
      setErr(true);
      setTimeout(() => setErr(false), 1500);
      setPwd("");
    }
  };

  return (
    <div style={{ display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", height:"100%", background:"#FAF7F2", padding:32 }}>
      <svg width="52" height="52" viewBox="0 0 52 52" style={{ marginBottom:20 }}>
        <rect x="21" y="4" width="10" height="44" rx="4" fill="#7B3535"/>
        <rect x="6" y="16" width="40" height="10" rx="4" fill="#7B3535"/>
      </svg>
      <div style={{ fontFamily:"Georgia,serif", fontSize:22, fontWeight:700, color:"#7B3535", marginBottom:6 }}>Predigerplanung</div>
      <div style={{ fontSize:13, color:"#7A6A6A", marginBottom:32 }}>Bitte Passwort eingeben</div>
      <input
        type="password" value={pwd}
        onChange={e => setPwd(e.target.value)}
        onKeyDown={e => e.key === "Enter" && check()}
        placeholder="Passwort"
        style={{ width:"100%", maxWidth:280, border:`1.5px solid ${err?"#E55":"#E8DDD5"}`, borderRadius:10, padding:"12px 14px", fontSize:16, outline:"none", textAlign:"center", background:err?"#FFF5F5":"#FFFFFF", transition:"border 0.2s" }}
      />
      <button onClick={check} style={{ marginTop:14, background:"#7B3535", color:"white", border:"none", borderRadius:10, padding:"12px 0", fontSize:15, fontWeight:700, cursor:"pointer", width:"100%", maxWidth:280, fontFamily:"Georgia,serif" }}>
        Anmelden
      </button>
      {err && <div style={{ marginTop:10, color:"#C44", fontSize:13 }}>Falsches Passwort</div>}
    </div>
  );
}

// ─── Firebase Verbinden (simpel) ──────────────────────────────────
// Firebase wird einmalig vom Admin eingerichtet.
// Hier wird nur die fertige Config eingefügt, um sich zu verbinden.
function FirebaseSetupScreen({ onDone, onSkip }) {
  const [cfg, setCfg] = useAuthState("");
  const [err, setErr] = useAuthState("");
  const [ok, setOk] = useAuthState(false);

  const tryConnect = () => {
    setErr("");
    try {
      // Extrahiere das JS-Objekt und werte es sicher aus (kein JSON.parse nötig)
      const match = cfg.match(/\{[\s\S]*\}/);
      if (!match) { setErr("Kein Konfigurations-Objekt gefunden."); return; }
      // eslint-disable-next-line no-new-func
      const config = (new Function("return (" + match[0] + ")"))();
      if (!config.apiKey) {
        setErr("apiKey fehlt in der Config.");
        return;
      }
      if (!config.databaseURL) {
        setErr("databaseURL fehlt! Bitte lies den Hinweis unten.");
        return;
      }
      const success = fbSaveConfig(config);
      if (success) {
        setOk(true);
        setTimeout(onDone, 1000);
      } else {
        setErr("Verbindung fehlgeschlagen. Config prüfen.");
      }
    } catch(e) {
      setErr("Fehler: " + e.message);
    }
  };

  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100%", background:"#FAF7F2" }}>
      <div style={{ background:"#7B3535", padding:"16px 16px 14px" }}>
        <div style={{ color:"white", fontFamily:"Georgia,serif", fontSize:15, fontWeight:700 }}>Mit Firebase verbinden</div>
        <div style={{ color:"rgba(255,255,255,0.7)", fontSize:11, marginTop:2 }}>Cloud-Synchronisation einrichten</div>
      </div>

      <div style={{ flex:1, overflowY:"auto", padding:"20px 16px" }}>
        {/* Info */}
        <div style={{ background:"#FFF9F0", border:"1px solid #E8DDD5", borderRadius:10, padding:"12px 14px", marginBottom:20 }}>
          <div style={{ fontSize:13, fontWeight:700, color:"#7B3535", marginBottom:6 }}>Was ist das?</div>
          <div style={{ fontSize:13, color:"#2C1F1F", lineHeight:1.7 }}>
            Firebase ermöglicht es, dass <strong>mehrere Geräte</strong> dieselbe Planung sehen und bearbeiten können.<br/><br/>
            Die Firebase-Datenbank wurde bereits vom <strong>Administrator</strong> eingerichtet. Du brauchst nur die <strong>Verbindungs-Config</strong> einzufügen.
          </div>
        </div>

        {/* Config eingeben */}
        <div style={{ fontSize:12, fontWeight:700, color:"#7A6A6A", marginBottom:6, textTransform:"uppercase", letterSpacing:"0.05em" }}>
          Firebase-Config einfügen
        </div>
        <div style={{ fontSize:12, color:"#7A6A6A", marginBottom:8, lineHeight:1.6 }}>
          Den <code style={{ background:"#F3EDE3", padding:"1px 4px", borderRadius:3 }}>firebaseConfig</code>-Block vom Administrator anfordern und hier einfügen:
        </div>
        <textarea
          value={cfg}
          onChange={e => setCfg(e.target.value)}
          placeholder={`const firebaseConfig = {\n  apiKey: "AIza...",\n  authDomain: "projekt.firebaseapp.com",\n  databaseURL: "https://projekt-rtdb.europe-west1.firebasedatabase.app",\n  projectId: "projekt",\n  ...\n};`}
          style={{ width:"100%", height:160, border:"1.5px solid #E8DDD5", borderRadius:8, padding:10, fontSize:11, fontFamily:"monospace", resize:"none", outline:"none", background:"#FAFAFA", color:"#333" }}
        />
        {err && <div style={{ fontSize:12, color:"#C44", marginTop:8, padding:"8px 10px", background:"#FFF5F5", borderRadius:6 }}>{err}</div>}
        {ok && <div style={{ fontSize:13, color:"#4A6741", fontWeight:700, marginTop:8 }}>✓ Verbunden! Daten werden synchronisiert.</div>}
      </div>

      <div style={{ padding:"12px 16px 8px", borderTop:"1px solid #E8DDD5" }}>
        <button onClick={tryConnect} disabled={!cfg.trim() || ok}
          style={{ width:"100%", background: ok ? "#4A6741" : (cfg.trim() ? "#7B3535" : "#C0A0A0"), color:"white", border:"none", borderRadius:10, padding:"13px", fontSize:15, fontWeight:700, cursor:cfg.trim()?"pointer":"default", fontFamily:"Georgia,serif", marginBottom:10 }}>
          {ok ? "✓ Verbunden" : "Verbinden"}
        </button>
        <button onClick={onSkip} style={{ width:"100%", background:"none", border:"none", color:"#B09090", fontSize:13, cursor:"pointer", padding:"6px" }}>
          Überspringen (nur lokal speichern)
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, FirebaseSetupScreen });
