"use client";

/**
 * app/join/page.js — invite trust/confirmation screen (Phase 5, H6).
 *
 * The blob rides in the URL FRAGMENT (#invite=…) so the token never reaches the
 * server/referrer logs (H1). The fragment is client-only, so we decode it here
 * for DISPLAY and hand the raw blob to the server for authoritative validation.
 *
 * The load-bearing trust element is the "Connects to <host>" pill (H6): the user
 * verifies WHERE they're connecting before anything is written. Nothing is
 * persisted until they confirm; no local secret is migrated into the new config.
 */

import { useEffect, useState } from 'react';

/** Lightweight client-side decode for DISPLAY only. The server re-validates. */
function clientDecode(blob) {
  try {
    const bin = atob(blob.replace(/-/g, '+').replace(/_/g, '/'));
    const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
    const json = JSON.parse(new TextDecoder().decode(bytes));
    if (json.v !== 1 || typeof json.url !== 'string') return null;
    return { url: json.url, org: typeof json.org === 'string' ? json.org : null, token: json.token, anonKey: json.anonKey };
  } catch {
    return null;
  }
}

export default function JoinPage() {
  const [decoded, setDecoded] = useState(null);
  const [blob, setBlob] = useState('');
  const [status, setStatus] = useState('reading'); // reading | ready | bad | joining | error
  const [error, setError] = useState('');

  useEffect(() => {
    const hash = typeof window !== 'undefined' ? window.location.hash : '';
    const m = hash.match(/[#&]invite=([^&]+)/);
    const raw = m ? decodeURIComponent(m[1]) : '';
    if (!raw) { setStatus('bad'); return; }
    const d = clientDecode(raw);
    if (!d || !d.url || !d.token) { setStatus('bad'); return; }
    setBlob(raw);
    setDecoded(d);
    setStatus('ready');
  }, []);

  let host = '';
  try { host = decoded ? new URL(decoded.url).host : ''; } catch { host = ''; }

  async function confirmJoin() {
    setError('');
    setStatus('joining');
    try {
      const res = await fetch('/api/auth/join-bootstrap', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ invite: blob }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        throw new Error(data.message || "Couldn't reach that project. Check the link with whoever invited you.");
      }
      // The bearer token is now held server-side in an httpOnly cookie (set by
      // join-bootstrap). After sign-in, /onboarding/org hands off to
      // /api/orgs/join-complete, which redeems it and clears the cookie. No
      // client-side token handling — robust across provider hops and new tabs.
      window.location.href = '/login?supabase=1&next=' + encodeURIComponent('/onboarding/org');
    } catch (err) {
      setError(err.message);
      setStatus('error');
    }
  }

  if (status === 'reading') {
    return <main className="join-shell"><p className="account-meta">Reading invite…</p></main>;
  }
  if (status === 'bad') {
    return (
      <main className="join-shell">
        <p>This invite link is invalid or has expired. Ask the sender for a new one.</p>
      </main>
    );
  }

  return (
    <main className="join-shell" style={{ maxWidth: 480, margin: '0 auto', padding: '48px 16px' }}>
      <div style={{ textAlign: 'center', marginBottom: 8 }}>◆ madarX</div>
      <div className="account-meta" style={{ textAlign: 'center', color: 'var(--accent-600)', letterSpacing: '0.08em' }}>
        JOIN ORGANIZATION
      </div>
      <h1 style={{ textAlign: 'center' }}>Join {decoded.org || 'this organization'}</h1>

      <div className="admin-panel">
        <div className="admin-record"><span>Organization</span><strong>{decoded.org || '—'}</strong></div>
        <div className="admin-record">
          <span>Connects to</span>
          {/* H6: the host pill is the anti-phishing trust element — real, selectable
              text (never an image), prominent + monospace so a wrong host is obvious. */}
          <code style={{ fontFamily: 'monospace', padding: '2px 8px', border: '1px solid var(--accent-500)', borderRadius: 6 }}>
            {host || decoded.url}
          </code>
        </div>
      </div>

      <p className="account-meta">
        This connects your local app to {decoded.org || 'this'} cloud workspace. Your existing
        local data stays on your machine.
      </p>

      {error ? <p role="alert" style={{ color: 'var(--accent-600)' }}>{error}</p> : null}

      <button
        className="admin-btn-primary"
        style={{ width: '100%' }}
        disabled={status === 'joining'}
        onClick={confirmJoin}
      >
        {status === 'joining' ? 'Joining…' : `Join ${decoded.org || 'organization'}`}
      </button>
      <div style={{ textAlign: 'center', marginTop: 12 }}>
        <a href="/" className="account-meta">Cancel</a>
      </div>
    </main>
  );
}
