/* === Share homebook screen ===
   Peer-to-peer founder invites for the beta. Each household gets a small
   number of "founder invites" (3 by default — see founderInviteCap in
   data.jsx). When a household member sends one, the recipient gets an
   email that drops them onto the join page with the code pre-filled, and
   on accept they create their OWN brand-new homebook with themselves as
   primary.

   Different from the family-member invite (Family screen → "Invite to
   household") — that one adds someone INTO this household. This one
   spawns a fresh household for someone else.

   Server contract:
   - RPC `create_founder_invite(p_invited_name text, p_invited_email text)`
     returns { code, expires_at }. The function enforces the cap server-side
     by counting invites the caller has issued; the client mirror in state
     (founderInviteHistory[]) is for UI only.
   - Email goes through the existing `send-invite-email` Edge Function with
     kind: 'primary', same as PrimaryInviteModal.
*/

function ShareHomebookScreen({ state, setState, isDemo }) {
  const cap = state.founderInviteCap || 3;
  const history = state.founderInviteHistory || [];
  const used = history.length;
  const remaining = Math.max(0, cap - used);
  const exhausted = remaining === 0;

  const [firstName, setFirstName] = React.useState('');
  const [lastName,  setLastName]  = React.useState('');
  const [email,     setEmail]     = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [emailStatus, setEmailStatus] = React.useState('idle'); // idle|sending|sent|failed
  const [lastSent, setLastSent] = React.useState(null); // { name, email, code, expiresAt }

  const emailLooksValid = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim());
  const canSubmit = !exhausted && firstName.trim() && lastName.trim() && emailLooksValid(email);

  const fullName       = `${firstName.trim()} ${lastName.trim()}`.trim();
  const householdLabel = lastName.trim() ? `the ${lastName.trim()} Homebook` : 'their homebook';

  const sendEmailFor = async (codeToSend, recipientFirstName, recipientEmail) => {
    if (!codeToSend) return;
    const inviterPrimary = (state.family || []).find(m => m.role === 'primary')
                        || (state.family || []).find(m => m.id === 'self');
    const inviterName = inviterPrimary?.name || '';
    const link = `https://app.homebook.tools/?join=${encodeURIComponent(codeToSend)}`;

    setEmailStatus('sending');
    try {
      const { error: fnErr } = await supabaseClient.functions.invoke('send-invite-email', {
        body: {
          recipient_email:  recipientEmail,
          recipient_name:   recipientFirstName,
          inviter_name:     inviterName,
          household_label:  householdLabel,
          code:             codeToSend,
          share_link:       link,
          kind:             'primary',
        },
      });
      setEmailStatus(fnErr ? 'failed' : 'sent');
    } catch {
      setEmailStatus('failed');
    }
  };

  const submit = async () => {
    if (exhausted) return;
    if (!canSubmit) {
      if (!firstName.trim() || !lastName.trim()) setError('First and last name are both required.');
      else if (!email.trim())                    setError("We need their email to send the invite.");
      else                                       setError("That email doesn't look right — double-check it.");
      return;
    }
    setError('');
    setBusy(true);
    setEmailStatus('idle');
    try {
      // Demo mode: skip the RPC entirely. Mint a fake code so the UI
      // still demonstrates the success state without touching Supabase.
      let data, rpcErr;
      if (isDemo) {
        await new Promise(r => setTimeout(r, 600)); // mimic latency
        data = {
          code: 'DEMO-' + Math.random().toString(36).slice(2, 6).toUpperCase(),
          expires_at: new Date(Date.now() + 30 * 86400000).toISOString(),
        };
      } else {
        ({ data, error: rpcErr } = await supabaseClient.rpc('create_founder_invite', {
          p_invited_name:  fullName,
          p_invited_email: email.trim(),
        }));
        // Fallback: if the 0002 migration hasn't been applied yet, the new
        // RPC won't exist server-side. Admin users (the founder) can still
        // mint primary invites via the original create_primary_invite RPC,
        // which is gated to the admins table. Non-admins will get a
        // surfaced auth error from that fallback that the catch handles.
        if (rpcErr && /function .* does not exist|could not find the function/i.test(rpcErr.message || '')) {
          ({ data, error: rpcErr } = await supabaseClient.rpc('create_primary_invite', {
            p_invited_name:  fullName,
            p_invited_email: email.trim(),
          }));
        }
      }
      if (rpcErr) throw rpcErr;

      const newCode = data?.code || '';
      const expiresAt = data?.expires_at || '';

      // Mirror the invite into state so the UI counter and history list
      // update without waiting for a refetch. Server is the source of truth
      // for the cap — if it disagrees, server wins on the next attempt.
      //
      // We deliberately do NOT persist the invite code into state. The
      // recipient owns the code (it's in their email); the inviter doesn't
      // need to see it and shouldn't be able to share it on their behalf.
      // The code is held in component state (`lastSent`) only so the
      // "Try email again" button can re-send the email without minting a
      // fresh invite — it's lost on reload, which is fine.
      const recipientFirstName = firstName.trim();
      const recipientEmail = email.trim();
      setState(s => ({
        ...s,
        founderInviteHistory: [
          ...(s.founderInviteHistory || []),
          { id: 'fi' + Date.now().toString(36), name: fullName, email: recipientEmail, sentAt: new Date().toISOString(), expiresAt },
        ],
      }));
      setLastSent({ name: fullName, firstName: recipientFirstName, email: recipientEmail, code: newCode, expiresAt });

      // Reset the form so they can fire off another one.
      setFirstName(''); setLastName(''); setEmail('');

      if (isDemo) {
        // Don't try to invoke the email Edge Function in demo mode.
        setEmailStatus('sent');
      } else {
        await sendEmailFor(newCode, recipientFirstName, recipientEmail);
      }
    } catch (e) {
      const msg = e?.message || 'Could not send invite. Try again?';
      // The RPC's cap-exceeded error surfaces here too — show it cleanly.
      setError(/founder invite/i.test(msg) ? msg : msg);
    } finally {
      setBusy(false);
    }
  };

  const onKeyDown = (ev) => { if (ev.key === 'Enter') submit(); };

  const formatSentAt = (iso) => {
    try {
      const d = new Date(iso);
      const days = Math.floor((Date.now() - d.getTime()) / (1000 * 60 * 60 * 24));
      if (days === 0) return 'today';
      if (days === 1) return 'yesterday';
      return `${days} days ago`;
    } catch { return ''; }
  };

  return (
    <>
      <div className="page-head">
        <div>
          <div className="page-sub">Beta · {remaining} of {cap} invites remaining</div>
          <h1 className="page-title">Share homebook</h1>
        </div>
      </div>

      <div style={{ padding: '24px 28px 32px', maxWidth: 640, display: 'flex', flexDirection: 'column', gap: 16 }}>

        {/* Hero / pitch */}
        <div className="card" style={{ background: 'var(--paper-2)' }}>
          <div className="card-section">Help homebook grow</div>
          <p style={{ fontSize: 13.5, lineHeight: 1.6, color: 'var(--ink-2)', margin: '4px 0 8px' }}>
            You're using homebook during the beta — the best way to support us is to help a friend or family member start their own. They'll get a fresh homebook of their own, completely free during the beta. No credit card, no commitment.
          </p>
          <p className="muted mono" style={{ fontSize: 11, lineHeight: 1.5, marginTop: 6 }}>
            Each household gets {cap} founder invites. We keep the number small on purpose — share with people who'll genuinely use it.
          </p>
        </div>

        {/* Send a new invite */}
        <div className="card">
          <div className="card-section">
            Invite a friend
            <span className="eyebrow num">{remaining} left</span>
          </div>

          {exhausted ? (
            <div className="muted" style={{ fontSize: 12.5, padding: '12px 2px', lineHeight: 1.6 }}>
              You've used all {cap} of your founder invites. Thank you for sharing homebook — your invitees can each share with friends of their own once they're set up.
            </div>
          ) : (
            <>
              <div className="row gap-sm">
                <div className="field" style={{ flex: 1 }}>
                  <span className="field-label">First name</span>
                  <input className="input" value={firstName} onChange={e => setFirstName(e.target.value)}
                    onKeyDown={onKeyDown} placeholder="Sarah" disabled={busy} />
                </div>
                <div className="field" style={{ flex: 1 }}>
                  <span className="field-label">Last name</span>
                  <input className="input" value={lastName} onChange={e => setLastName(e.target.value)}
                    onKeyDown={onKeyDown} placeholder="Andringa" disabled={busy} />
                </div>
              </div>
              <div className="field">
                <span className="field-label">Their email</span>
                <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)}
                  onKeyDown={onKeyDown} placeholder="sarah@example.com" disabled={busy} />
                <span className="field-hint">We'll send the invite to their inbox.</span>
              </div>
              {lastName.trim() && (
                <div className="auth-attribution" style={{ marginTop: 10 }}>
                  Their household will be called <strong>{householdLabel}</strong>.
                </div>
              )}
              {error && <div className="auth-error" style={{ marginTop: 10 }}>{error}</div>}
              <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
                <button className="btn primary" onClick={submit} disabled={busy || !canSubmit}>
                  {busy ? 'Sending…' : 'Send invite'}
                </button>
              </div>
            </>
          )}
        </div>

        {/* Most recent send — confirmation card */}
        {lastSent && (
          <div className="card" style={{ borderColor: 'var(--pos)' }}>
            <div className="card-section">
              Invite sent
              <span className="eyebrow">{emailStatus === 'sent' ? '✓ Email delivered' : emailStatus === 'sending' ? 'Sending…' : emailStatus === 'failed' ? 'Email failed' : ''}</span>
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)' }}>
              <strong>{lastSent.firstName}</strong> ({lastSent.email}) will get an email with their invite code. When they accept, a fresh <em>homebook</em> household will be created with them as primary.
            </div>
            {emailStatus === 'failed' && (
              <button className="btn" style={{ marginTop: 10 }}
                onClick={() => sendEmailFor(lastSent.code, lastSent.firstName, lastSent.email)}>
                Try email again
              </button>
            )}
          </div>
        )}

        {/* History */}
        {history.length > 0 && (
          <div className="card list-card">
            <div className="card-section">
              Sent invites
              <span className="eyebrow num">{history.length}</span>
            </div>
            {[...history].reverse().map(h => {
              // Pending until the recipient accepts. Once we wire the
              // server-side status query, this can flip to 'accepted' /
              // 'expired'. For now, "pending" is the only state we know.
              const isExpired = h.expiresAt && new Date(h.expiresAt).getTime() < Date.now();
              return (
                <div key={h.id} className="txn">
                  <div className="txn-date">{formatSentAt(h.sentAt)}</div>
                  <div>
                    <div className="txn-merchant">{h.name}</div>
                    <div className="txn-meta">
                      <span className="muted">{h.email}</span>
                    </div>
                  </div>
                  <div></div>
                  <span className="eyebrow muted" style={{ fontSize: 10 }}>
                    {isExpired ? 'Expired' : 'Pending'}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { ShareHomebookScreen });
