/* The public entry points at the existing Access-protected /admin scope.
   Private navigation is fetched only after that full-page sign-in handoff. */
const leadershipResources = [
  { id: 'donation-receipts', title: 'Donation receipts', href: '/admin/receipts', label: 'Open donation receipts',
    description: 'Create, save, print, and email acknowledgments for cash, check, and in-kind gifts.' },
  { id: 'scholarships', title: 'Scholarships', href: '/admin', label: 'Open scholarship workspace',
    description: 'Review applications, follow scholarship progress, and access records for your assigned role.' },
  { id: 'camp-interest', title: 'Camp interest results', href: '/admin/camp-interest', label: 'View camp interest results',
    description: 'Explore family interest, potential camper totals, and planning reports for summer camp.' },
];

function LeadershipLogin() {
  return <section className="wk-leadership wk-container" aria-labelledby="leadership-login-title">
    <div className="wk-leadership-login">
      <div>
        <p className="wk-leadership-kicker">Western Kentucky Chapter</p>
        <h1 id="leadership-login-title">Leadership login</h1>
        <p className="wk-leadership-intro">One place for the work we do together.</p>
        <p>Officers, board members, and assigned volunteers can sign in here to reach the chapter’s private resources.</p>
      </div>
      <div className="wk-leadership-card">
        <h2>Welcome back</h2>
        <p>Use your approved email address to sign in. You’ll receive a verification code by email.</p>
        <a className="wk-leadership-primary" href="/admin/leadership">Sign in to Leadership <span aria-hidden="true">→</span></a>
        <p className="wk-leadership-note">Chapter and approved personal email addresses are welcome. Your assigned access determines which resources appear after sign-in.</p>
        <p className="wk-leadership-note">Need access? <a href="/contact">Contact chapter leadership</a> to have your email approved.</p>
      </div>
    </div>
  </section>;
}

function LeadershipHub() {
  const [session, setSession] = React.useState(null);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    const controller = new AbortController();
    const load = async () => {
      try {
        const response = await fetch('/admin/leadership-api/session', {
          credentials: 'same-origin', cache: 'no-store', redirect: 'error',
          headers: { Accept: 'application/json' }, signal: controller.signal,
        });
        const result = await response.json().catch(() => null);
        if (!response.ok || !result?.success || !Array.isArray(result.resources)) {
          throw new Error(response.status === 503
            ? 'Leadership access is temporarily unavailable. Please contact the website administrator.'
            : 'Your session could not be verified. Please sign in through Leadership login.');
        }
        if (!controller.signal.aborted) setSession(result);
      } catch (failure) {
        if (!controller.signal.aborted) setError(failure instanceof TypeError
          ? 'Your session could not be verified. Please sign in through Leadership login.' : failure.message);
      } finally { if (!controller.signal.aborted) setLoading(false); }
    };
    load();
    // Never restore a previously visible private hub after sign-out.
    const restored = (event) => { if (event.persisted) window.location.reload(); };
    window.addEventListener('pageshow', restored);
    return () => { controller.abort(); window.removeEventListener('pageshow', restored); };
  }, []);
  const resources = leadershipResources.filter((resource) => session?.resources.includes(resource.id));
  return <section className="wk-leadership wk-container" aria-labelledby="leadership-hub-title">
    <header className="wk-leadership-header">
      <div><p className="wk-leadership-kicker">Chapter leadership</p>
        <h1 id="leadership-hub-title">Leadership hub</h1>
        <p className="wk-leadership-intro">Your chapter resources, together.</p>
        {session && <p className="wk-leadership-identity">Signed in as {session.email}</p>}
      </div>
      {session && <a href="/cdn-cgi/access/logout" onClick={() => setSession(null)}>Sign out</a>}
    </header>
    {loading && <p role="status">Checking your leadership access…</p>}
    {error && <div className="wk-leadership-card" role="alert"><h2>Sign-in required</h2><p>{error}</p><a href="/leadership">Leadership login</a></div>}
    {session && <React.Fragment>
      <div className="wk-leadership-resources">
        {resources.map((resource) => <article className="wk-leadership-card" key={resource.id}>
          <h2>{resource.title}</h2><p>{resource.description}</p>
          <a className="wk-leadership-resource-link" href={resource.href}>{resource.label} <span aria-hidden="true">→</span></a>
        </article>)}
      </div>
      {!resources.length && <div className="wk-leadership-card"><h2>No resources assigned yet</h2><p>You’re signed in, but no resources are currently available for this email. Contact chapter leadership if you expected access.</p></div>}
      <p className="wk-leadership-note">Only resources available to your account appear here. For help with access, <a href="/contact">contact chapter leadership</a>.</p>
    </React.Fragment>}
  </section>;
}

window.Pages = window.Pages || {};
window.Pages.leadership = LeadershipLogin;
window.LeadershipHub = LeadershipHub;
