// Account widget for TeachCue-iOS.html. Sits at the top-right of the page
// (outside the phone-frame demo) so the auth state belongs to the website,
// not the simulated iOS app inside the frame.
//
// Sign-in flow:
//   1. User clicks the button → GET /api/auth/apple/start?return_to=...
//   2. Worker redirects to Apple's authorize URL
//   3. Apple POSTs id_token to /api/auth/apple/callback (form_post mode)
//   4. Worker verifies, sets HttpOnly cookie, redirects back here
//   5. This widget re-fetches /api/me and renders the signed-in state

const { useState, useEffect, useCallback } = React;

function AccountWidget() {
  const [state, setState] = useState({ kind: 'loading' }); // 'loading' | 'guest' | 'signedIn'
  const [user, setUser] = useState(null);

  const refresh = useCallback(async () => {
    try {
      const r = await fetch('/api/me', { credentials: 'include' });
      if (r.ok) {
        const data = await r.json();
        setUser(data.user);
        setState({ kind: 'signedIn' });
        return;
      }
      // 401 = no session. Anything else = backend not configured yet — fall
      // back to guest so the UI doesn't dead-lock during local dev.
      setUser(null);
      setState({ kind: 'guest' });
    } catch {
      setState({ kind: 'guest' });
    }
  }, []);

  useEffect(() => { refresh(); }, [refresh]);

  // Refresh on focus — covers the case where the user signed in via a
  // popup or another tab.
  useEffect(() => {
    const onFocus = () => refresh();
    window.addEventListener('focus', onFocus);
    return () => window.removeEventListener('focus', onFocus);
  }, [refresh]);

  const signIn = () => {
    const returnTo = encodeURIComponent(location.pathname + location.search);
    location.href = `/api/auth/apple/start?return_to=${returnTo}`;
  };

  const signOut = async () => {
    setState({ kind: 'loading' });
    await fetch('/api/auth/signout', { method: 'POST', credentials: 'include' });
    setUser(null);
    setState({ kind: 'guest' });
  };

  // Two-step confirm matches the iOS flow + satisfies App Store §5.1.1(v).
  // We surface the same "revoke at appleid.apple.com" hint the server
  // returns so the user knows how to fully cut TeachCue's Apple link.
  const deleteAccount = async () => {
    if (!confirm(
      'Delete your TeachCue account?\n\n'
      + 'This permanently removes your synced slide decks, subscription record, and notes. '
      + 'You can sign in again later but your synced data will be gone.'
    )) return;
    if (!confirm('Last chance — really delete? This cannot be undone.')) return;

    setState({ kind: 'loading' });
    try {
      const r = await fetch('/api/account', { method: 'DELETE', credentials: 'include' });
      const body = await r.json().catch(() => ({}));
      if (!r.ok) {
        alert('Delete failed: ' + (body.error || r.status));
        await refresh();
        return;
      }
      alert(
        'Your TeachCue account is gone.\n\n'
        + 'To also revoke this app from your Apple ID, visit:\n'
        + (body.revoke_at_apple || 'https://appleid.apple.com/account/manage')
      );
      setUser(null);
      setState({ kind: 'guest' });
    } catch (e) {
      alert('Delete failed: ' + e.message);
      await refresh();
    }
  };

  const baseStyle = {
    position: 'fixed', top: 22, right: 26, zIndex: 100,
    display: 'flex', alignItems: 'center', gap: 12,
    fontFamily: "'Inter', -apple-system, system-ui, sans-serif",
    fontSize: 13, color: '#1E1A15',
  };

  if (state.kind === 'loading') {
    return (
      <div style={baseStyle}>
        <span style={{ color: '#756B5E' }}>Loading…</span>
      </div>
    );
  }

  if (state.kind === 'signedIn' && user) {
    const initial = (user.displayName || user.email || '?').slice(0, 1).toUpperCase();
    return (
      <div style={baseStyle}>
        <div style={{
          width: 30, height: 30, borderRadius: '50%',
          background: 'linear-gradient(135deg,#EF8F64 0%,#C8562E 100%)',
          color: '#FFF7EF', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 600, fontSize: 13,
        }}>{initial}</div>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.2 }}>
          <span style={{ fontWeight: 600 }}>{user.displayName || user.email || 'Account'}</span>
          <span style={{ fontSize: 10, color: '#756B5E', textTransform: 'uppercase', letterSpacing: 1 }}>
            {user.plan} plan
          </span>
        </div>
        <button
          onClick={signOut}
          style={{
            marginLeft: 6, padding: '6px 12px', fontSize: 12,
            background: 'transparent', border: '1px solid #D9CDB8',
            borderRadius: 8, color: '#756B5E', cursor: 'pointer',
            fontFamily: 'inherit',
          }}
        >Sign out</button>
        <button
          onClick={deleteAccount}
          style={{
            padding: '6px 12px', fontSize: 12,
            background: 'transparent', border: '1px solid rgba(217,81,63,0.4)',
            borderRadius: 8, color: '#D9513F', cursor: 'pointer',
            fontFamily: 'inherit',
          }}
          title="Permanently delete your TeachCue account"
        >Delete</button>
      </div>
    );
  }

  // Guest — show the Apple-branded button.
  return (
    <div style={baseStyle}>
      <button
        onClick={signIn}
        style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 16px', fontSize: 13, fontWeight: 500,
          background: '#000', color: '#fff', border: 0, borderRadius: 10,
          cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: '0 4px 14px rgba(0,0,0,0.18)',
        }}
        aria-label="Sign in with Apple"
      >
        <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor" aria-hidden="true">
          <path d="M11.6 8.5c0-2 1.6-2.9 1.7-3-0.9-1.3-2.4-1.5-2.9-1.5-1.2-0.1-2.4 0.7-3 0.7-0.6 0-1.6-0.7-2.6-0.7-1.3 0-2.6 0.8-3.3 2-1.4 2.4-0.4 6 1 8 0.7 0.9 1.5 2 2.5 1.9 1 0 1.4-0.6 2.6-0.6 1.2 0 1.5 0.6 2.6 0.6 1.1 0 1.8-1 2.5-1.9 0.8-1.1 1.1-2.1 1.1-2.2-0.1 0-2.2-0.8-2.2-3.3M9.7 2.7c0.5-0.6 0.9-1.5 0.8-2.4-0.8 0-1.7 0.5-2.2 1.2-0.5 0.6-0.9 1.5-0.8 2.3 0.9 0.1 1.8-0.4 2.2-1.1"/>
        </svg>
        Sign in with Apple
      </button>
    </div>
  );
}

// Mount immediately into a dedicated container so it's independent of the
// main App tree (which is the demo phone frame). The container is created
// in TeachCue-iOS.html.
const accountRoot = document.getElementById('account-widget');
if (accountRoot) {
  ReactDOM.createRoot(accountRoot).render(<AccountWidget />);
}
