// invite.jsx — Invite acceptance page.
// Rendered when the user visits /invite/:token

const { useState: useInvState, useEffect: useInvEffect, useRef: useInvRef } = React;

function InviteAcceptPage({ token, isSignedIn, familyData, getAuthHeaders, openSignIn, openSignUp, onAccepted }) {
  const [status, setStatus]             = useInvState('loading');
  const [familyName, setFamilyName]     = useInvState('');
  const [invitedEmail, setInvitedEmail] = useInvState('');
  const [accepting, setAccepting]       = useInvState(false);
  const [acceptError, setAcceptError]   = useInvState('');
  const [done, setDone]                 = useInvState(false);
  const signUpContainerRef              = useInvRef(null);
  const { clerkRef, clerkLoadedRef }    = useAuthState();

  // Load invite details
  useInvEffect(() => {
    if (!token) { setStatus('notfound'); return; }
    fetch(`/api/invite/${token}`)
      .then(r => r.json())
      .then(data => {
        if (data.status === 'pending') {
          setFamilyName(data.familyName || '');
          setInvitedEmail(data.invitedEmail || '');
          setStatus('pending');
        } else if (data.status === 'accepted') {
          setStatus('accepted');
        } else if (data.status === 'expired') {
          setStatus('expired');
        } else {
          setStatus('notfound');
        }
      })
      .catch(() => setStatus('error'));
  }, [token]);

  // Mount Clerk sign-up widget when invite is pending and user isn't signed in.
  // afterSignUpUrl sends them back to this same /invite/:token page; on return
  // isSignedIn will be true and the auto-accept effect below fires.
  useInvEffect(() => {
    if (status !== 'pending' || isSignedIn || !signUpContainerRef.current) return;

    function tryMount() {
      if (clerkLoadedRef.current && clerkRef.current) {
        clerkRef.current.mountSignUp(signUpContainerRef.current, {
          afterSignUpUrl: window.location.href,
          afterSignInUrl: window.location.href,
          appearance:     window.CLERK_APPEARANCE,
        });
        return;
      }
      setTimeout(tryMount, 50);
    }
    tryMount();

    return () => {
      try {
        if (clerkRef.current && signUpContainerRef.current) {
          clerkRef.current.unmountSignUp(signUpContainerRef.current);
        }
      } catch {}
    };
  }, [status, isSignedIn]);

  // Auto-accept as soon as invite is pending and user is signed in.
  useInvEffect(() => {
    if (status === 'pending' && isSignedIn && !accepting && !done) {
      handleAccept();
    }
  }, [isSignedIn, status]);

  async function handleAccept() {
    if (!isSignedIn) return;
    setAccepting(true);
    setAcceptError('');
    try {
      const hdrs = await getAuthHeaders();
      console.log('[invite] accepting token', token.slice(0, 8) + '…', 'hasAuthHeader:', !!hdrs.Authorization);

      const res = await fetch(`/api/invite/${token}/accept`, {
        method: 'POST',
        headers: hdrs,
      });

      let data;
      try { data = await res.json(); } catch { data = {}; }
      console.log('[invite] accept response', res.status, data);

      if (res.status === 401) {
        setAcceptError('Please sign in to accept this invite.');
        setAccepting(false);
        openSignIn();
        return;
      }
      if (!res.ok) {
        setAcceptError(data.error || `Accept failed (HTTP ${res.status})`);
        setAccepting(false);
        return;
      }
      setDone(true);
      setTimeout(() => onAccepted && onAccepted(), 1800);
    } catch (err) {
      console.error('[invite] accept fetch error', err);
      setAcceptError('Something went wrong — check your connection and try again.');
      setAccepting(false);
    }
  }

  return (
    <div className="invite-page">
      <div className="invite-card">
        <div className="invite-logo">Family Cookbook</div>

        {status === 'loading' && (
          <p className="invite-body">Loading invitation…</p>
        )}

        {status === 'error' && (
          <>
            <h2 className="invite-heading">Something went wrong</h2>
            <p className="invite-body">We couldn't load this invitation. Please try again.</p>
          </>
        )}

        {status === 'notfound' && (
          <>
            <h2 className="invite-heading">Invite not found</h2>
            <p className="invite-body">This invite link is invalid or no longer exists.</p>
          </>
        )}

        {status === 'expired' && (
          <>
            <h2 className="invite-heading">Invite expired</h2>
            <p className="invite-body">This invite link has expired. Ask the family owner to send a new one.</p>
          </>
        )}

        {status === 'accepted' && !done && (
          <>
            <h2 className="invite-heading">Already accepted</h2>
            <p className="invite-body">This invite has already been used. Sign in to access the cookbook.</p>
          </>
        )}

        {status === 'pending' && !done && (() => {
          const alreadyInFamily = isSignedIn && familyData && familyData.family;
          return (
            <>
              <div className="invite-icon">🍽️</div>
              <h2 className="invite-heading">You're invited to join</h2>
              <div className="invite-family-name">{familyName}</div>

              {alreadyInFamily ? (
                <>
                  <p className="invite-body">
                    You're already a member of <strong>{familyData.family.name}</strong>. You'd need to leave your current family before joining another.
                  </p>
                  <button className="primary-btn big invite-cta" onClick={onAccepted}>
                    Go to my cookbook
                  </button>
                </>
              ) : isSignedIn ? (
                <>
                  <p className="invite-body">{accepting ? 'Joining…' : 'Click below to accept and start cooking together.'}</p>
                  {acceptError && <div className="invite-error">{acceptError}</div>}
                  {!accepting && (
                    <button className="primary-btn big invite-cta" onClick={handleAccept}>
                      Accept Invitation
                    </button>
                  )}
                </>
              ) : (
                <>
                  <p className="invite-body">Create an account or sign in to join <strong>{familyName}</strong>.</p>
                  {acceptError && <div className="invite-error">{acceptError}</div>}
                  <div ref={signUpContainerRef} className="invite-clerk-widget" />
                </>
              )}
            </>
          );
        })()}

        {done && (
          <>
            <div className="invite-icon">✓</div>
            <h2 className="invite-heading">You're in!</h2>
            <p className="invite-body">Welcome to <strong>{familyName}</strong>. Taking you to the cookbook…</p>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { InviteAcceptPage });
