// admin-app.jsx — STANDALONE admin console root (deploy at admin.<yourdomain>)
// Loaded only by admin.html. Decoupled from the consumer app (app.jsx).
const { useState: useAd, useEffect: useAdE, useMemo: useAdM } = React;

// demo seed (admin-only, so this file is self-contained)
const ADMIN_SEED_PENDING = [
  { id: "priya", name: "Priya Nair", city: "Mumbai", phone: "+91 98••• ••231", aadhaarName: "Priya Nair",     aadhaarLast4: "3847", upiId: "priya.n@okicici", idPhotoUrl: null, selfieUrl: null, videoUrl: null },
  { id: "sana",  name: "Sana Q.",    city: "Remote", phone: "+91 90••• ••884", aadhaarName: "Sana Qureshi",   aadhaarLast4: "8721", upiId: "sana.q@paytm",   idPhotoUrl: null, selfieUrl: null, videoUrl: null },
];
const ADMIN_SEED_META = {
  [TASKS[0] && TASKS[0].id]: { status: "completed", assignedTo: "arjun" },
  [TASKS[6] && TASKS[6].id]: { status: "assigned",  assignedTo: "__me" },
  [TASKS[2] && TASKS[2].id]: { status: "completed", assignedTo: "__me" },
  [TASKS[3] && TASKS[3].id]: { status: "assigned",  assignedTo: "tomi" },
};

const adFull = { minHeight: "100vh", display: "grid", placeItems: "center", background: "var(--paper)", padding: 24, fontFamily: "var(--sans)" };

function AdminApp() {
  const demoMode = !isSupabaseConfigured();
  const [authUser, setAuthUser]       = useAd(null);
  const [authProfile, setAuthProfile] = useAd(null);
  const [authLoading, setAuthLoading] = useAd(!demoMode);
  const [pendingSubs, setPendingSubs] = useAd(demoMode ? ADMIN_SEED_PENDING : []);
  const [users, setUsers]             = useAd([]);
  const [dbTasks, setDbTasks]         = useAd([]);
  const [metaOv, setMetaOv]           = useAd(demoMode ? ADMIN_SEED_META : {});
  const [toast, setToast]             = useAd(null);

  const showToast = (m) => { setToast(m); clearTimeout(window.__att); window.__att = setTimeout(() => setToast(null), 2600); };

  const ensureProfile = async (user) => {
    const { profile } = await Profiles.get(user.id);
    setAuthUser(user); setAuthProfile(profile); setAuthLoading(false);
  };

  // ── auth (real mode only) ──
  useAdE(() => {
    if (demoMode) return;
    Auth.getSession().then(({ session }) => { if (session?.user) ensureProfile(session.user); else setAuthLoading(false); });
    const unsub = Auth.onAuthChange((event, session) => {
      if (session?.user) ensureProfile(session.user);
      else { setAuthUser(null); setAuthProfile(null); }
    });
    return unsub;
  }, []);

  const isAdmin = demoMode ? true : !!authProfile?.isAdmin;

  // ── load admin data (real mode, admins only) ──
  useAdE(() => {
    if (demoMode || !authUser || !isAdmin) return;
    Promise.all([Verification.listPending(), Admin.allUsers(), Tasks.list()]).then(([p, u, t]) => {
      setPendingSubs(p.subs || []); setUsers(u.users || []); setDbTasks(t.tasks || []);
    });
  }, [authUser, isAdmin]);

  const allTasks = demoMode ? TASKS : dbTasks;
  const getMeta = (taskId) => metaOv[taskId] || { status: (allTasks.find(t => t.id === taskId) || {}).status || "open" };

  // ── handlers ──
  const approveSub = async (sub) => {
    if (!demoMode) await Verification.setStatus(sub.id, "verified");
    setPendingSubs(s => s.filter(x => x.id !== sub.id));
    showToast(`${sub.name} approved ✓`);
  };
  const rejectSub = async (sub, reason) => {
    if (!demoMode) await Verification.setStatus(sub.id, "rejected", reason);
    setPendingSubs(s => s.filter(x => x.id !== sub.id));
    showToast(`${sub.name}'s submission was rejected.`);
  };
  const onRelease = async (taskId) => {
    if (!demoMode) await Assignments.releasePayment(taskId, "Released by admin");
    setMetaOv(m => ({ ...m, [taskId]: { ...(m[taskId] || {}), status: "completed" } }));
    showToast("Payment released.");
  };
  const onRefund = async (taskId) => {
    if (!demoMode) await Tasks.updateStatus(taskId, "cancelled");
    setMetaOv(m => ({ ...m, [taskId]: { ...(m[taskId] || {}), status: "cancelled" } }));
    showToast("Marked as refunded.");
  };

  const adminVerifications = useAdM(() => pendingSubs.map(s => ({
    id: s.id, name: s.name, city: s.city || "", submitted: "recently", status: "pending",
    docType: "Aadhaar Card", docId: s.aadhaarLast4 ? `•••• ${s.aadhaarLast4}` : "Submitted",
    hasSelfie: !!s.selfieUrl, hasVideo: !!s.videoUrl,
    email: s.email || "", phone: s.phone || "",
    aadhaarName: s.aadhaarName || "", upiId: s.upiId || "",
    idPhotoUrl: s.idPhotoUrl || null, selfieUrl: s.selfieUrl || null, videoUrl: s.videoUrl || null,
  })), [pendingSubs]);

  const completedFixed = allTasks.filter(t => getMeta(t.id).status === "completed" && t.pay && t.pay.kind === "fixed");
  const stats = {
    totalUsers: demoMode ? Object.keys(PEOPLE).length : users.length,
    pendingVerifications: pendingSubs.length,
    totalTransactions: completedFixed.length,
    revenue: completedFixed.reduce((s, t) => s + (t.pay.amount || 0), 0),
    revenueCur: "₹",
  };

  // logo / "back to app" → main consumer domain (apex). Locally that's "/".
  const go = (v) => { if (v === "home") window.location.href = "/"; };
  const signOut = async () => { await Auth.signOut(); setAuthUser(null); setAuthProfile(null); };

  // ── render ──
  if (authLoading) {
    return <div style={adFull}><div style={{ fontFamily: "var(--display)", fontSize: 20, color: "var(--ink-2)" }}>Loading…</div></div>;
  }

  if (!demoMode && !authUser) {
    return (
      <div>
        <div style={{ position: "fixed", top: 18, right: 20, zIndex: 50 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-2)" }}>Admin console</div>
        </div>
        <AuthGate demoMode={false} onAuth={() => {}} backUrl="/" backLabel="Back to app" />
      </div>
    );
  }

  if (!isAdmin) {
    return (
      <div style={adFull}>
        <div style={{ textAlign: "center", maxWidth: 380 }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--ink-3)", color: "var(--ink-2)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}><Icon name="shield" size={30} /></div>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, letterSpacing: "-0.02em", margin: "0 0 8px", color: "var(--ink)" }}>Not an admin account</h1>
          <p style={{ fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5, margin: "0 0 24px" }}>This console is for administrators only. Sign in with an admin account, or head back to the app.</p>
          <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
            <Button variant="ghost" onClick={signOut}>Sign out</Button>
            <Button onClick={() => (window.location.href = "/")}>Back to app</Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <AdminPanel go={go} data={{
        stats,
        verifications: adminVerifications,
        onApprove: approveSub,
        onReject: rejectSub,
        tasks: allTasks,
        getMeta,
        onRelease,
        onRefund,
      }} />
      {/* sign-out chip (real mode) */}
      {!demoMode && authUser && (
        <button onClick={signOut} style={{ position: "fixed", top: 16, right: 18, zIndex: 60, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 999, padding: "8px 14px", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13, fontWeight: 600, color: "var(--ink-2)", display: "inline-flex", alignItems: "center", gap: 7 }}>
          <Icon name="logout" size={15} /> Sign out
        </button>
      )}
      {toast && (
        <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 200, background: "var(--ink)", color: "var(--paper)", padding: "14px 22px", borderRadius: 999, fontFamily: "var(--sans)", fontSize: 15, fontWeight: 600, display: "flex", alignItems: "center", gap: 10, boxShadow: "0 16px 40px -12px rgba(20,14,6,.5)", whiteSpace: "nowrap" }}>
          <span style={{ color: "var(--green)" }}><Icon name="check" size={18} stroke={2.6} /></span> {toast}
        </div>
      )}
    </>
  );
}

class AdminErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { console.error("Admin crashed:", error, info); }
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div style={adFull}>
        <div style={{ textAlign: "center", maxWidth: 440 }}>
          <div style={{ fontSize: 44, marginBottom: 14 }}>😵</div>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26, margin: "0 0 8px", color: "var(--ink)" }}>Something went wrong</h1>
          <p style={{ fontSize: 15, color: "var(--ink-2)", margin: "0 0 20px" }}>The admin console hit an error. Reloading usually fixes it.</p>
          <button onClick={() => location.reload()} style={{ padding: "12px 24px", borderRadius: 999, border: "none", background: "var(--clay)", color: "#fff", fontWeight: 700, fontSize: 15, cursor: "pointer", fontFamily: "var(--sans)" }}>Reload</button>
        </div>
      </div>
    );
  }
}

ReactDOM.createRoot(document.getElementById("root")).render(<AdminErrorBoundary><AdminApp /></AdminErrorBoundary>);
