/* === Claim member screen ===
   Shown to a signed-in user whose auth.user.id isn't yet linked to any
   family[] entry in their household. This is the "which one are you?"
   moment for users who joined via invite — accept_invite() puts them in
   households.member_ids[] but doesn't touch state.family[]. Linking the
   auth user to a specific family entry is what lets the SMS feature
   scope @member-targeted spend to the right personal budget (and any
   future per-member features).

   Two paths:
     1. Pick an existing unclaimed family entry — sets authUserId on it.
     2. "I'm not in this list" — append a new family entry with the
        typed name and the user's authUserId.

   The App-level gate skips this screen entirely for users whose
   authUserId is already on a family entry (the typical primary-signup
   case) and for households with no family entries yet (brand-new
   founders — they'll add family during onboarding instead). */

function ClaimMemberScreen({ state, setState, userId }) {
  const family = state.family || [];
  const unclaimed = family.filter(m => !m.authUserId);

  const [mode, setMode] = React.useState(unclaimed.length > 0 ? 'pick' : 'new');
  const [newName, setNewName] = React.useState('');
  const [newColor, setNewColor] = React.useState(() => {
    const used = new Set(family.map(m => m.color));
    return Object.keys(TAG_COLORS).find(c => !used.has(c)) || 'ochre';
  });

  const claim = (memberId) => {
    setState(s => ({
      ...s,
      family: (s.family || []).map(m =>
        m.id === memberId ? { ...m, authUserId: userId } : m
      ),
    }));
  };

  const createAndClaim = () => {
    const trimmed = newName.trim();
    if (!trimmed) return;
    const initials = nameInitials(trimmed);
    const slug = trimmed.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'member';
    const id = `${slug}-${Date.now().toString(36).slice(-4)}`;
    setState(s => ({
      ...s,
      family: [...(s.family || []), {
        id, name: trimmed, initials, color: newColor, role: 'partner', budget: 0,
        authUserId: userId,
      }],
    }));
  };

  return (
    <div className="auth-shell">
      <div className="auth-card">
        <div className="auth-brand">homebook</div>
        <div className="auth-sub">
          {mode === 'pick'
            ? "Welcome. Which family member are you?"
            : "Welcome. What name should the household see you as?"}
        </div>

        {mode === 'pick' && (
          <>
            <div className="claim-list">
              {unclaimed.map(m => (
                <button key={m.id} type="button" className="claim-row" onClick={() => claim(m.id)}>
                  <span className="claim-dot" style={{ background: TAG_COLORS[m.color] || TAG_COLORS.ochre }} />
                  <span className="claim-name">{m.name}</span>
                </button>
              ))}
            </div>
            <button type="button" className="btn ghost" onClick={() => setMode('new')}>
              I'm not in this list — add me
            </button>
          </>
        )}

        {mode === 'new' && (
          <>
            <div className="field">
              <span className="field-label">Your name</span>
              <input
                className="input"
                autoFocus
                value={newName}
                onChange={e => setNewName(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') createAndClaim(); }}
                placeholder="e.g. Matt"
              />
            </div>
            <div className="field">
              <span className="field-label">Color</span>
              <div className="color-grid">
                {Object.entries(TAG_COLORS).map(([key, hex]) => (
                  <div key={key}
                    className={`color-swatch ${newColor === key ? 'selected' : ''}`}
                    style={{ background: hex }}
                    onClick={() => setNewColor(key)} />
                ))}
              </div>
            </div>
            <button type="button" className="btn primary" onClick={createAndClaim} disabled={!newName.trim()}>
              Continue
            </button>
            {unclaimed.length > 0 && (
              <button type="button" className="btn ghost" onClick={() => setMode('pick')}>
                ← Pick from the existing list
              </button>
            )}
          </>
        )}
      </div>
    </div>
  );
}

// Gate predicate — used by App in index.html.
// True when the signed-in user has no claim on any family entry AND
// there's at least one entry to choose from. Brand-new households
// (empty family) skip the screen and go straight to onboarding.
function needsToClaimMember(state, userId) {
  const family = state?.family || [];
  if (family.length === 0) return false;
  return !family.some(m => m.authUserId === userId);
}

Object.assign(window, { ClaimMemberScreen, needsToClaimMember });
