// =============================================================================
// Authentication — hooks + UI components
// =============================================================================
// Provides:
//   - useAuth() hook  — current user, loading state, signIn/signOut methods
//   - <AuthModal />   — login/signup modal (magic link + Google + Microsoft)
//   - <AuthButton />  — small button to show in the sidebar/topbar
//
// If Supabase isn't configured, all of these silently no-op and the app
// behaves exactly as before (anonymous localStorage mode).
// =============================================================================

// ─────────────────────────────────────────────────────────────────────────────
// Auth context — single source of truth for auth state across the whole app.
// Wrap the app with <AuthProvider>, then any component can call useAuth().
// This prevents each component from independently fetching the session and
// avoids loading-flicker when navigating between pages.
// ─────────────────────────────────────────────────────────────────────────────

const AuthContext = React.createContext(null);

function useAuth() {
  const ctx = React.useContext(AuthContext);
  if (ctx) return ctx;
  // Fallback for components rendered outside AuthProvider — disabled-ish state
  return {
    user: null, profile: null, isAdmin: false, isAuthenticated: false,
    loading: false, isAvailable: false,
    signInWithMagicLink: async () => {}, signInWithGoogle: async () => {},
    signInWithMicrosoft: async () => {}, signOut: async () => {}
  };
}

function AuthProvider({ children }) {
  const [user, setUser] = React.useState(null);
  const [profile, setProfile] = React.useState(null);  // { role, full_name, ... }
  const [loading, setLoading] = React.useState(true);

  const sb = window.supabaseClient;

  // Initial session load + subscribe to changes
  React.useEffect(() => {
    if (!sb) {
      setLoading(false);
      return;
    }

    let mounted = true;

    sb.auth.getSession().then(({ data: { session } }) => {
      if (!mounted) return;
      setUser(session?.user || null);
      setLoading(false);
    });

    const { data: { subscription } } = sb.auth.onAuthStateChange(
      async (_event, session) => {
        if (!mounted) return;
        setUser(session?.user || null);
      }
    );

    return () => {
      mounted = false;
      subscription?.unsubscribe();
    };
  }, [sb]);

  // Load profile (role, full_name) whenever user changes
  React.useEffect(() => {
    if (!sb || !user) {
      setProfile(null);
      return;
    }
    let cancelled = false;
    sb.from("users")
      .select("role, full_name, email, locale")
      .eq("id", user.id)
      .maybeSingle()
      .then(({ data }) => {
        if (cancelled) return;
        setProfile(data || null);
      });
    return () => { cancelled = true; };
  }, [sb, user]);

  // Drain pending sync queue once authenticated
  React.useEffect(() => {
    if (user && window.Storage) {
      window.Storage.syncPending().catch(() => {});
    }
  }, [user]);

  // GDPR consent metadata — included on first signup. Re-sending is harmless.
  const consentMeta = (marketingConsent) => ({
    consented_at: new Date().toISOString(),
    consent_version: window.APP_CONFIG?.legal?.version || "2026-05",
    marketing_consent: !!marketingConsent
  });

  const signInWithMagicLink = React.useCallback(async (email, opts = {}) => {
    if (!sb) throw new Error("Supabase not configured");
    const { error } = await sb.auth.signInWithOtp({
      email,
      options: {
        emailRedirectTo: window.location.origin,
        data: consentMeta(opts.marketingConsent)
      }
    });
    if (error) throw error;
  }, [sb]);

  const signInWithGoogle = React.useCallback(async (opts = {}) => {
    if (!sb) throw new Error("Supabase not configured");
    const { error } = await sb.auth.signInWithOAuth({
      provider: "google",
      options: {
        redirectTo: window.location.origin,
        queryParams: {
          // Pass consent through OAuth state via local storage hint
        }
      }
    });
    if (error) throw error;
    // Stash consent locally; backfilled on next session
    try { localStorage.setItem("pm_pending_consent", JSON.stringify(consentMeta(opts.marketingConsent))); } catch (e) {}
  }, [sb]);

  const signInWithMicrosoft = React.useCallback(async (opts = {}) => {
    if (!sb) throw new Error("Supabase not configured");
    const { error } = await sb.auth.signInWithOAuth({
      provider: "azure",
      options: {
        redirectTo: window.location.origin,
        scopes: "email openid profile"
      }
    });
    if (error) throw error;
    try { localStorage.setItem("pm_pending_consent", JSON.stringify(consentMeta(opts.marketingConsent))); } catch (e) {}
  }, [sb]);

  const signOut = React.useCallback(async () => {
    if (!sb) return;
    await sb.auth.signOut();
    setUser(null);
    setProfile(null);
  }, [sb]);

  const value = {
    user,
    profile,
    isAdmin: profile?.role === "admin",
    isAuthenticated: !!user,
    loading,
    signInWithMagicLink,
    signInWithGoogle,
    signInWithMicrosoft,
    signOut,
    isAvailable: !!sb  // false = Supabase not configured, hide auth UI
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

// ─────────────────────────────────────────────────────────────────────────────
// <AuthModal /> — login/signup popup
// ─────────────────────────────────────────────────────────────────────────────

function AuthModal({ open, onClose }) {
  const auth = useAuth();
  const [email, setEmail] = React.useState("");
  const [step, setStep] = React.useState("input"); // 'input' | 'sent' | 'loading'
  const [error, setError] = React.useState(null);
  const [tosAccepted, setTosAccepted] = React.useState(false);
  const [marketingOk, setMarketingOk] = React.useState(false);

  if (!open) return null;
  if (!auth.isAvailable) return null;

  const submitMagicLink = async (e) => {
    e.preventDefault();
    setError(null);
    if (!tosAccepted) {
      setError("Trebuie să accepți Termenii și Politica de Confidențialitate.");
      return;
    }
    if (!email.trim() || !email.includes("@")) {
      setError("Introdu o adresă de email validă.");
      return;
    }
    setStep("loading");
    try {
      await auth.signInWithMagicLink(email.trim(), { marketingConsent: marketingOk });
      setStep("sent");
    } catch (err) {
      setError(err.message || "Eroare la trimiterea link-ului.");
      setStep("input");
    }
  };

  const oauthHandler = (provider) => async () => {
    setError(null);
    if (!tosAccepted) {
      setError("Trebuie să accepți Termenii și Politica de Confidențialitate.");
      return;
    }
    try {
      if (provider === "google") await auth.signInWithGoogle({ marketingConsent: marketingOk });
      else if (provider === "microsoft") await auth.signInWithMicrosoft({ marketingConsent: marketingOk });
    } catch (err) {
      setError(err.message || "Eroare la autentificare.");
    }
  };

  return (
    <div className="auth-modal-backdrop" onClick={onClose}>
      <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
        <button className="auth-modal-close" onClick={onClose} aria-label="Închide">✕</button>

        <div className="auth-modal-head">
          <h2 className="auth-modal-title">Bun venit</h2>
          <p className="auth-modal-sub">
            Conectează-te pentru a-ți sincroniza progresul pe toate dispozitivele.
          </p>
        </div>

        {step === "sent" ? (
          <div className="auth-sent">
            <div className="auth-sent-icon">✉</div>
            <div className="auth-sent-title">Ți-am trimis un link de autentificare</div>
            <div className="auth-sent-sub">
              Verifică inbox-ul la <strong>{email}</strong>. Click pe link și ești
              autentificat automat. Nu uita să verifici și folderul Spam.
            </div>
            <button className="btn ghost" onClick={() => { setStep("input"); setEmail(""); }}>
              Schimbă adresa
            </button>
          </div>
        ) : (
          <>
            <form onSubmit={submitMagicLink} className="auth-form">
              <label className="auth-label">
                <span>Email</span>
                <input
                  type="email"
                  className="txt"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="nume@example.ro"
                  disabled={step === "loading"}
                  autoFocus
                />
              </label>
              {error && <div className="auth-error">{error}</div>}
              <button
                type="submit"
                className="btn primary"
                disabled={step === "loading"}
                style={{ width: "100%" }}
              >
                {step === "loading" ? "Se trimite..." : "Trimite link de autentificare"}
              </button>
            </form>

            <div className="auth-divider">
              <span>sau</span>
            </div>

            <div className="auth-providers">
              <button
                className="btn ghost auth-provider-btn"
                onClick={oauthHandler("google")}
                disabled={step === "loading"}
              >
                <span style={{ fontWeight: 600 }}>G</span>
                Continuă cu Google
              </button>
              <button
                className="btn ghost auth-provider-btn"
                onClick={oauthHandler("microsoft")}
                disabled={step === "loading"}
              >
                <span style={{ fontWeight: 600 }}>⊞</span>
                Continuă cu Microsoft
              </button>
            </div>

            <div className="auth-consent">
              <label className="auth-consent-row">
                <input
                  type="checkbox"
                  checked={tosAccepted}
                  onChange={(e) => setTosAccepted(e.target.checked)}
                />
                <span>
                  Accept <a href="/legal/terms.html" target="_blank" rel="noopener">Termenii și Condițiile</a>
                  {" "}și{" "}
                  <a href="/legal/privacy.html" target="_blank" rel="noopener">Politica de Confidențialitate</a>.
                  <span className="auth-consent-required"> *obligatoriu</span>
                </span>
              </label>
              <label className="auth-consent-row">
                <input
                  type="checkbox"
                  checked={marketingOk}
                  onChange={(e) => setMarketingOk(e.target.checked)}
                />
                <span>
                  Doresc să primesc noutăți despre platformă și conținut nou (opțional).
                </span>
              </label>
            </div>

            <div className="auth-fineprint">
              Datele tale sunt stocate în Uniunea Europeană (Frankfurt, Germania).
              Poți exporta sau șterge contul oricând din setări.
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// <AuthButton /> — small button shown in the sidebar/topbar
// ─────────────────────────────────────────────────────────────────────────────

function AuthButton() {
  const auth = useAuth();
  const [modalOpen, setModalOpen] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);

  if (!auth.isAvailable) return null;  // Supabase not configured
  if (auth.loading) return null;

  if (!auth.isAuthenticated) {
    return (
      <>
        <button
          className="auth-cta-btn"
          onClick={() => setModalOpen(true)}
          title="Conectare / Cont"
        >
          <span className="auth-cta-icon">◔</span>
          <span className="auth-cta-label">Conectează-te</span>
        </button>
        <AuthModal open={modalOpen} onClose={() => setModalOpen(false)} />
      </>
    );
  }

  // Logged in — show user pill with dropdown
  const displayName = auth.profile?.full_name || auth.user?.email || "Cont";
  const initials = (displayName.match(/\b\w/g) || []).join("").slice(0, 2).toUpperCase();

  return (
    <div className="auth-user-wrap">
      <button className="auth-user-btn" onClick={() => setMenuOpen(!menuOpen)}>
        <span className="auth-user-avatar">{initials}</span>
        <span className="auth-user-name">{displayName}</span>
        {auth.isAdmin && <span className="auth-admin-badge">admin</span>}
      </button>
      {menuOpen && (
        <>
          <div className="auth-menu-backdrop" onClick={() => setMenuOpen(false)}></div>
          <div className="auth-menu">
            <div className="auth-menu-header">
              <div style={{ fontWeight: 600 }}>{displayName}</div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{auth.user?.email}</div>
            </div>
            <button className="auth-menu-item" onClick={async () => {
              await auth.signOut();
              setMenuOpen(false);
              // Reload so anonymous mode kicks in cleanly
              window.location.reload();
            }}>
              Deconectare
            </button>
          </div>
        </>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// <PrivacySettings /> — GDPR-required user controls
// Used as a section/page accessible from sidebar or profile menu.
// ─────────────────────────────────────────────────────────────────────────────

function PrivacySettings({ go }) {
  const auth = useAuth();
  const [exporting, setExporting] = React.useState(false);
  const [deleting, setDeleting] = React.useState(false);
  const [confirmDelete, setConfirmDelete] = React.useState("");

  const handleExport = async () => {
    setExporting(true);
    try {
      await window.Storage.exportMyData();
    } catch (e) {
      alert("Eroare la export: " + (e.message || e));
    } finally {
      setExporting(false);
    }
  };

  const handleDelete = async () => {
    const expectedEmail = auth.user?.email || "";
    if (confirmDelete.trim().toLowerCase() !== expectedEmail.toLowerCase()) {
      alert("Tastează exact adresa ta de email pentru a confirma.");
      return;
    }
    setDeleting(true);
    try {
      // Capture email before deletion so we can show it in the final message
      const deletedEmail = expectedEmail;
      await window.Storage.deleteMyAccount();
      alert(
        "Contul tău (" + deletedEmail + ") a fost șters definitiv.\n\n" +
        "Vei primi o confirmare pe email în câteva minute.\n\n" +
        "Mulțumim că ai încercat platforma."
      );
      window.location.href = "/";
    } catch (e) {
      alert("Eroare la ștergere: " + (e.message || e));
      setDeleting(false);
    }
  };

  return (
    <div>
      <div className="main-head">
        <div className="crumb">Cont · Confidențialitate</div>
        <h1 className="section-title">Confidențialitate și date</h1>
        <p className="section-lede">
          Conform GDPR, ai dreptul deplin asupra datelor tale. De aici poți
          descărca tot ce stocăm despre tine sau șterge definitiv contul.
        </p>
      </div>

      {auth.loading && (
        <div className="privacy-panel">
          <p>Verificare autentificare...</p>
        </div>
      )}

      {!auth.loading && !auth.isAuthenticated && (
        <div className="privacy-panel">
          <h3>Nu ești conectat</h3>
          <p>
            Datele tale sunt stocate doar local în browser-ul acesta. Pentru a-ți
            sincroniza progresul și a folosi aceste opțiuni, conectează-te.
          </p>
        </div>
      )}

      <div className="privacy-panel">
        <h3>Profilul tău</h3>
        {auth.isAuthenticated ? (
          <>
            <p>
              <strong>Email:</strong> {auth.user?.email}<br />
              <strong>Nume:</strong> {auth.profile?.full_name || "—"}<br />
              <strong>Rol:</strong> {auth.profile?.role || "user"}<br />
              <strong>Locație date:</strong> Uniunea Europeană (Frankfurt, Germania)
            </p>
          </>
        ) : (
          <p>Conectează-te pentru a vedea profilul.</p>
        )}
      </div>

      <div className="privacy-panel">
        <h3>Descarcă datele tale</h3>
        <p>
          Toate informațiile pe care platforma le stochează despre tine,
          într-un singur fișier JSON. Include progresul, proiectele, simulările
          și rezultatele quiz-urilor. (Articolul 20 GDPR — dreptul la portabilitate)
        </p>
        <div className="privacy-action-row">
          <button className="btn primary" onClick={handleExport} disabled={exporting}>
            {exporting ? "Se exportă..." : "↓ Descarcă datele mele (JSON)"}
          </button>
        </div>
      </div>

      {auth.isAuthenticated && (
        <div className="privacy-panel privacy-danger-zone">
          <h3>Șterge contul definitiv</h3>
          <p>
            Toate datele tale vor fi șterse permanent: progres, proiecte,
            simulări, rezultate. <strong>Această acțiune nu poate fi anulată.</strong>
            {" "}(Articolul 17 GDPR — dreptul la ștergere)
          </p>
          <p>
            Pentru confirmare, tastează adresa ta de email{" "}
            (<strong>{auth.user?.email}</strong>) în câmpul de mai jos.
            Vei primi o confirmare pe email după ștergere.
          </p>
          <div className="privacy-action-row">
            <input
              className="txt"
              type="email"
              value={confirmDelete}
              onChange={(e) => setConfirmDelete(e.target.value)}
              placeholder={auth.user?.email || "email@exemplu.ro"}
              style={{ maxWidth: 320, margin: 0 }}
              autoComplete="off"
            />
            <button
              className="btn-danger"
              onClick={handleDelete}
              disabled={
                deleting ||
                confirmDelete.trim().toLowerCase() !== (auth.user?.email || "").toLowerCase()
              }
            >
              {deleting ? "Se șterge..." : "Șterge contul definitiv"}
            </button>
          </div>
        </div>
      )}

      <div className="privacy-panel">
        <h3>Documente legale</h3>
        <p>
          <a href="/legal/privacy.html" target="_blank" rel="noopener">Politica de Confidențialitate</a> ·{" "}
          <a href="/legal/terms.html" target="_blank" rel="noopener">Termeni și Condiții</a> ·{" "}
          <a href="/legal/cookies.html" target="_blank" rel="noopener">Politica Cookies</a>
        </p>
        <p>
          Pentru întrebări legate de prelucrarea datelor:{" "}
          <a href={`mailto:${window.APP_CONFIG?.app?.contactEmail || "ionut.filea@gmail.com"}`}>
            {window.APP_CONFIG?.app?.contactEmail || "ionut.filea@gmail.com"}
          </a>
        </p>
      </div>

      <div className="foot-actions">
        <button className="btn ghost" onClick={() => go("intro")}>← Înapoi</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// <SiteFooter /> — legal links visible on every page
// ─────────────────────────────────────────────────────────────────────────────

function SiteFooter({ go }) {
  return (
    <footer className="site-footer">
      <div className="site-footer-links">
        <a href="/legal/privacy.html" target="_blank" rel="noopener">Confidențialitate</a>
        <a href="/legal/terms.html" target="_blank" rel="noopener">Termeni</a>
        <a href="/legal/cookies.html" target="_blank" rel="noopener">Cookies</a>
        <a href="#history" onClick={(e) => { e.preventDefault(); go("history"); }}>Istoricul meu</a>
        <a href="#privacy" onClick={(e) => { e.preventDefault(); go("privacy"); }}>Datele mele</a>
      </div>
      <div>
        © {new Date().getFullYear()} PM Interactive Hub ·{" "}
        Versiunea {window.APP_CONFIG?.app?.version || "0.2.0"}
      </div>
    </footer>
  );
}

Object.assign(window, { useAuth, AuthProvider, AuthModal, AuthButton, PrivacySettings, SiteFooter });
