(function () {
  const { useEffect, useMemo, useState } = React;

  function csvValue(value) {
    const text = Array.isArray(value) ? value.join('; ') : String(value ?? '');
    return `"${text.replaceAll('"', '""')}"`;
  }

  function downloadCsv(report) {
    const headings = [
      'Participant',
      'Email',
      'Status',
      'Current day',
      'Completed days',
      'Morning MAPs',
      'Evening MAPs',
      'Total MAPs',
      'Registered',
      'Last activity',
      'Converted to member',
    ];
    const lines = [
      headings.map(csvValue).join(','),
      ...(report.rows || []).map(row =>
        [
          row.name,
          row.email,
          row.challengeStatus,
          row.currentDay,
          row.completedDays,
          row.morningMaps,
          row.eveningMaps,
          row.totalMaps,
          row.registeredAt,
          row.lastActivity,
          row.convertedToMember ? 'Yes' : 'No',
        ]
          .map(csvValue)
          .join(',')
      ),
    ];
    const blob = new Blob([`\uFEFF${lines.join('\r\n')}`], {
      type: 'text/csv;charset=utf-8',
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `fruit-up-3-day-challenge-report-${new Date()
      .toISOString()
      .slice(0, 10)}.csv`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  function ChallengeAdminReports({ auth, functions, logo }) {
    const [user, setUser] = useState(null);
    const [report, setReport] = useState(null);
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState('');
    const [search, setSearch] = useState('');
    const [status, setStatus] = useState('all');

    useEffect(
      () =>
        auth.onAuthStateChanged(nextUser => {
          setUser(nextUser && !nextUser.isAnonymous ? nextUser : null);
        }),
      []
    );

    const signIn = async () => {
      setBusy(true);
      setError('');
      try {
        if (auth.currentUser?.isAnonymous) await auth.signOut();
        const provider = new firebase.auth.GoogleAuthProvider();
        const credential = await auth.signInWithPopup(provider);
        await credential.user.getIdToken(true);
        await functions.httpsCallable('claimChallengeOwnerAdmin')({});
        await credential.user.getIdToken(true);
        setUser(credential.user);
      } catch (signInError) {
        setError(
          signInError?.message ||
            'The administrator sign-in could not be completed.'
        );
      } finally {
        setBusy(false);
      }
    };

    const loadReport = async () => {
      setBusy(true);
      setError('');
      try {
        await auth.currentUser.getIdToken(true);
        const result = await functions.httpsCallable(
          'getChallengeAdminReport'
        )({});
        setReport(result.data);
      } catch (reportError) {
        setError(
          reportError?.message ||
            'The challenge report could not be loaded for this account.'
        );
      } finally {
        setBusy(false);
      }
    };

    const rows = useMemo(() => {
      const query = search.trim().toLowerCase();
      return (report?.rows || []).filter(row => {
        const matchesStatus =
          status === 'all' || row.challengeStatus === status;
        const matchesSearch =
          !query ||
          `${row.name || ''} ${row.email || ''}`
            .toLowerCase()
            .includes(query);
        return matchesStatus && matchesSearch;
      });
    }, [report, search, status]);

    const summary = report?.summary || {};
    return (
      <>
        <header className="sticky top-0 z-40 border-b border-white/10 bg-ink/95 backdrop-blur">
          <div className="mx-auto flex max-w-7xl items-center justify-between gap-4 px-5 py-3">
            <a href="./" className="flex items-center gap-3">
              <img src={logo} className="h-11 w-auto sm:h-14" alt="Fruit Up Til 5" />
              <span className="hidden text-xs font-extrabold uppercase tracking-widest text-leaf sm:inline">
                Challenge Reports
              </span>
            </a>
            {user && (
              <button
                className="btn btn-secondary !px-4 !py-3 text-xs"
                onClick={() => auth.signOut()}
              >
                Sign out
              </button>
            )}
          </div>
        </header>
        <main className="mx-auto max-w-7xl px-5 py-10 fade">
          <p className="eyebrow">Private administration</p>
          <h1 className="mt-3 text-4xl font-black sm:text-5xl">
            3-Day Challenge Reports
          </h1>
          <p className="mt-3 max-w-3xl text-white/60">
            Review registrations, challenge progress, MAP completion, and
            conversions without opening raw Firestore records.
          </p>

          {!user ? (
            <section className="card mt-8 max-w-xl rounded-3xl p-7">
              <h2 className="text-2xl font-black">Administrator sign-in</h2>
              <p className="mt-3 text-sm leading-relaxed text-white/60">
                Use the approved Google account for the 3-Day Challenge.
              </p>
              <button
                className="btn btn-primary mt-6 w-full"
                onClick={signIn}
                disabled={busy}
              >
                {busy ? 'Signing in…' : 'Sign in with Google'}
              </button>
            </section>
          ) : (
            <>
              <div className="mt-8 flex flex-wrap gap-3">
                <button
                  className="btn btn-primary"
                  onClick={loadReport}
                  disabled={busy}
                >
                  {busy ? 'Loading…' : report ? 'Refresh report' : 'Load report'}
                </button>
                {report && (
                  <button
                    className="btn btn-secondary"
                    onClick={() => downloadCsv(report)}
                  >
                    Download CSV
                  </button>
                )}
              </div>

              {report && (
                <>
                  <section className="mt-7 grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                    {[
                      ['Registered', summary.totalParticipants || 0],
                      ['Active', summary.activeParticipants || 0],
                      ['Completed', summary.completedParticipants || 0],
                      ['MAP entries', summary.totalMapEntries || 0],
                      ['Converted', summary.convertedMembers || 0],
                    ].map(([label, value]) => (
                      <article className="card rounded-2xl p-5" key={label}>
                        <p className="text-xs font-bold uppercase tracking-widest text-white/45">
                          {label}
                        </p>
                        <p className="mt-2 text-3xl font-black text-leaf">
                          {value}
                        </p>
                      </article>
                    ))}
                  </section>
                  <section className="mt-7 grid gap-4 sm:grid-cols-2">
                    <label>
                      <span className="label">Find a participant</span>
                      <input
                        className="field"
                        type="search"
                        value={search}
                        onChange={event => setSearch(event.target.value)}
                        placeholder="Name or email"
                      />
                    </label>
                    <label>
                      <span className="label">Challenge status</span>
                      <select
                        className="field"
                        value={status}
                        onChange={event => setStatus(event.target.value)}
                      >
                        <option value="all">All participants</option>
                        <option value="active">Active</option>
                        <option value="completed">Completed</option>
                      </select>
                    </label>
                  </section>
                  <section className="card mt-5 overflow-x-auto rounded-3xl">
                    <table className="min-w-full border-collapse text-left text-sm">
                      <thead className="border-b border-white/10 text-xs uppercase tracking-wider text-white/45">
                        <tr>
                          {[
                            'Participant',
                            'Status',
                            'Progress',
                            'Morning',
                            'Evening',
                            'Last activity',
                          ].map(heading => (
                            <th className="px-5 py-4" key={heading}>
                              {heading}
                            </th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {rows.map(row => (
                          <tr
                            className="border-b border-white/[.07] last:border-0"
                            key={row.participantId}
                          >
                            <td className="px-5 py-4">
                              <strong>{row.name}</strong>
                              <br />
                              <span className="text-white/45">{row.email}</span>
                            </td>
                            <td className="px-5 py-4 capitalize">
                              {row.challengeStatus}
                            </td>
                            <td className="px-5 py-4">
                              {row.completedDays} of 3 days
                            </td>
                            <td className="px-5 py-4">{row.morningMaps}</td>
                            <td className="px-5 py-4">{row.eveningMaps}</td>
                            <td className="px-5 py-4 text-white/55">
                              {row.lastActivity
                                ? new Date(row.lastActivity).toLocaleString()
                                : 'No MAP yet'}
                            </td>
                          </tr>
                        ))}
                        {!rows.length && (
                          <tr>
                            <td className="px-5 py-8 text-white/50" colSpan="6">
                              No participants match these filters.
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </section>
                  <p className="mt-4 text-xs text-white/40">
                    Private goals, phone numbers, obstacles, and MAP answers are
                    intentionally excluded from this operational report.
                  </p>
                </>
              )}
            </>
          )}
          {error && (
            <p className="mt-6 rounded-xl border border-red-400/25 bg-red-500/10 p-4 text-sm text-red-200">
              {error}
            </p>
          )}
        </main>
      </>
    );
  }

  window.ChallengeAdminReports = ChallengeAdminReports;
})();
