// INLEARN CRM — authentication + access allowlist.
//
// Live site: requires Google sign-in AND an allowlisted email before the CRM is
// shown. Any Google account can sign in, but non-allowlisted users see a
// "pending access" screen. Owners (hardcoded below) are always allowed and can
// manage the allowlist from inside the app.
// Preview / localhost: auth is bypassed so the design demo stays frictionless.
//
// NOTE: these Firebase web config values are public by design (they identify the
// project to Google; they are NOT secrets). Access is controlled by the Firestore
// security rules + this allowlist, not by hiding the config.

window.FIREBASE_CONFIG = {
  apiKey: "AIzaSyCu5QRDmeSBVA8OMG4vc-UXRdSEuL7wd30",
  authDomain: "leads-sales-crm-af3da.firebaseapp.com",
  projectId: "leads-sales-crm-af3da",
  storageBucket: "leads-sales-crm-af3da.firebasestorage.app",
  messagingSenderId: "562442835523",
  appId: "1:562442835523:web:87b457260bbaceb548e6f6",
};

// Bootstrap owners — always allowed, can manage the allowlist. Keep in sync with
// the isOwner() list in firestore.rules. Add more owner emails here as needed.
window.INLEARN_OWNERS = ['admin@inlearn.co.za'];

if (window.firebase && !window.firebase.apps.length) {
  window.firebase.initializeApp(window.FIREBASE_CONFIG);
}

const emailKey = (e) => (e || '').trim().toLowerCase();
const isOwnerEmail = (e) => window.INLEARN_OWNERS.indexOf(emailKey(e)) !== -1;

// ---------- Login screen ----------
function LoginScreen({ onSignIn, signingIn, error }) {
  return (
    <div className="h-full w-full flex items-center justify-center bg-slate-50 px-6">
      <div className="w-full max-w-sm">
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-8 text-center">
          <div className="mx-auto mb-5 w-12 h-12 rounded-xl bg-slate-900 text-white flex items-center justify-center brand-serif text-xl font-bold">IL</div>
          <h1 className="brand-serif text-2xl font-bold text-slate-900">INLEARN</h1>
          <p className="text-sm text-slate-500 mt-1">Leads &amp; Sales CRM</p>

          <button
            onClick={onSignIn}
            disabled={signingIn}
            className="mt-7 w-full flex items-center justify-center gap-3 rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-60 transition">
            <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.66-2.26 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.1a6.6 6.6 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.06l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
            </svg>
            {signingIn ? 'Signing in…' : 'Sign in with Google'}
          </button>

          {error && <p className="mt-4 text-xs text-rose-600">{error}</p>}
          <p className="mt-6 text-[11px] text-slate-400 leading-relaxed">
            Sign in with your Google account to access the INLEARN CRM.
          </p>
        </div>
      </div>
    </div>
  );
}

// ---------- Pending-access screen (signed in but not allowlisted) ----------
function AccessPendingScreen({ user, onSignOut }) {
  return (
    <div className="h-full w-full flex items-center justify-center bg-slate-50 px-6">
      <div className="w-full max-w-sm text-center">
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-8">
          <div className="mx-auto mb-5 w-12 h-12 rounded-xl bg-amber-100 text-amber-600 flex items-center justify-center">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
          </div>
          <h1 className="text-lg font-semibold text-slate-900">Access pending</h1>
          <p className="text-sm text-slate-500 mt-2 leading-relaxed">
            You're signed in as <span className="font-medium text-slate-700">{user.email}</span>, but this account isn't on the access list yet.
          </p>
          <p className="text-xs text-slate-400 mt-3">Ask an INLEARN admin to grant you access, then reload.</p>
          <button onClick={onSignOut} className="mt-6 w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition">
            Sign out
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- Owner-only access manager ----------
function AccessManagerModal({ onClose }) {
  const [rows, setRows] = React.useState(null); // null = loading
  const [email, setEmail] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');

  const db = window.firebase.firestore();

  const load = async () => {
    setError('');
    try {
      const snap = await db.collection('allowedUsers').get();
      setRows(snap.docs.map(d => ({ id: d.id, ...d.data() })));
    } catch (e) {
      setError('Could not load the access list. ' + (e.message || ''));
      setRows([]);
    }
  };
  React.useEffect(() => { load(); }, []);

  const add = async () => {
    const key = emailKey(email);
    if (!key || key.indexOf('@') === -1) { setError('Enter a valid email address.'); return; }
    setBusy(true); setError('');
    try {
      await db.collection('allowedUsers').doc(key).set({
        email: key,
        addedAt: new Date().toISOString(),
        addedBy: window.firebase.auth().currentUser.email,
      });
      setEmail('');
      await load();
    } catch (e) {
      setError('Could not add. ' + (e.message || ''));
    } finally { setBusy(false); }
  };

  const remove = async (id) => {
    setBusy(true); setError('');
    try {
      await db.collection('allowedUsers').doc(id).delete();
      await load();
    } catch (e) {
      setError('Could not remove. ' + (e.message || ''));
    } finally { setBusy(false); }
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 px-6" onClick={onClose}>
      <div className="w-full max-w-lg bg-white rounded-2xl border border-slate-200 shadow-xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200">
          <div>
            <h2 className="text-base font-semibold text-slate-900">Manage access</h2>
            <p className="text-xs text-slate-500">Only these Google accounts can use the CRM. Owners always have access.</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-700 p-1"><Icon.X width={18} height={18}/></button>
        </div>

        <div className="px-5 py-4">
          <div className="flex gap-2">
            <input
              value={email} onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') add(); }}
              placeholder="name@example.com" type="email"
              className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-400"/>
            <button onClick={add} disabled={busy}
              className="rounded-lg bg-indigo-600 text-white px-4 py-2 text-sm font-medium hover:bg-indigo-700 disabled:opacity-60">
              Add
            </button>
          </div>
          {error && <p className="mt-2 text-xs text-rose-600">{error}</p>}

          <div className="mt-4 max-h-72 overflow-auto divide-y divide-slate-100 border border-slate-100 rounded-lg">
            {window.INLEARN_OWNERS.map((o) => (
              <div key={o} className="flex items-center justify-between px-3 py-2.5">
                <div className="flex items-center gap-2.5 min-w-0">
                  <Avatar name={o} size={28} />
                  <span className="text-sm text-slate-700 truncate">{o}</span>
                </div>
                <span className="text-[11px] font-medium text-indigo-600 bg-indigo-50 rounded-full px-2 py-0.5">Owner</span>
              </div>
            ))}
            {rows === null && <div className="px-3 py-4 text-sm text-slate-400">Loading…</div>}
            {rows && rows.length === 0 && <div className="px-3 py-4 text-sm text-slate-400">No additional users yet. Add one above.</div>}
            {rows && rows.map((r) => (
              <div key={r.id} className="flex items-center justify-between px-3 py-2.5">
                <div className="flex items-center gap-2.5 min-w-0">
                  <Avatar name={r.email || r.id} size={28} />
                  <span className="text-sm text-slate-700 truncate">{r.email || r.id}</span>
                </div>
                <button onClick={() => remove(r.id)} disabled={busy}
                  className="text-xs text-rose-600 hover:text-rose-700 font-medium disabled:opacity-60">Remove</button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Auth gate ----------
function AuthGate({ children }) {
  // Preview / local: no auth required.
  if (window.INLEARN_IS_PREVIEW || !window.firebase) {
    return children;
  }

  const [user, setUser] = React.useState(undefined);   // undefined = resolving
  const [allowed, setAllowed] = React.useState(undefined); // undefined = checking
  const [signingIn, setSigningIn] = React.useState(false);
  const [error, setError] = React.useState('');
  const [accessOpen, setAccessOpen] = React.useState(false);

  React.useEffect(() => {
    return window.firebase.auth().onAuthStateChanged((u) => setUser(u || null));
  }, []);

  // Check the allowlist whenever the user changes.
  React.useEffect(() => {
    let cancelled = false;
    async function check() {
      if (!user) { setAllowed(undefined); return; }
      if (isOwnerEmail(user.email)) { if (!cancelled) setAllowed(true); return; }
      setAllowed(undefined);
      try {
        const doc = await window.firebase.firestore()
          .collection('allowedUsers').doc(emailKey(user.email)).get();
        if (!cancelled) setAllowed(doc.exists);
      } catch (e) {
        if (!cancelled) setAllowed(false);
      }
    }
    check();
    return () => { cancelled = true; };
  }, [user]);

  const signIn = async () => {
    setError(''); setSigningIn(true);
    try {
      const provider = new window.firebase.auth.GoogleAuthProvider();
      provider.setCustomParameters({ prompt: 'select_account' });
      await window.firebase.auth().signInWithPopup(provider);
    } catch (e) {
      setError(e && e.message ? e.message : 'Sign-in failed. Please try again.');
    } finally {
      setSigningIn(false);
    }
  };
  const signOut = () => window.firebase.auth().signOut();

  // Expose to the rest of the app (sidebar reads this).
  window.INLEARN_AUTH = {
    user: user || null,
    isOwner: !!(user && isOwnerEmail(user.email)),
    signOut,
    openAccessManager: () => setAccessOpen(true),
  };

  if (user === undefined) {
    return <div className="h-full w-full flex items-center justify-center bg-slate-50"><div className="text-slate-400 text-sm">Loading…</div></div>;
  }
  if (user === null) {
    return <LoginScreen onSignIn={signIn} signingIn={signingIn} error={error} />;
  }
  if (allowed === undefined) {
    return <div className="h-full w-full flex items-center justify-center bg-slate-50"><div className="text-slate-400 text-sm">Checking access…</div></div>;
  }
  if (allowed === false) {
    return <AccessPendingScreen user={user} onSignOut={signOut} />;
  }

  // Allowed → render the CRM (plus the access manager when an owner opens it).
  return (
    <>
      {children}
      {accessOpen && window.INLEARN_AUTH.isOwner &&
        <AccessManagerModal onClose={() => setAccessOpen(false)} />}
    </>
  );
}

window.AuthGate = AuthGate;
