// ─────────────────────────────────────────────────────────────
// SecondarySheet — chrome used by both Add-to-Group and Invite-to-Forest.
//
// Slides up over the primary ConnectSheet (which stays mounted in the
// background, so on dismiss we return there). Adds a back arrow that
// returns to the preview without closing the whole stack.
// ─────────────────────────────────────────────────────────────

function SecondarySheet({ title, subtitle, onBack, onClose, isOpen, children, footer }) {
  return (
    <>
      {/* Dimmer above the primary sheet */}
      <div onClick={onBack}
        style={{
          position: 'absolute', inset: 0,
          background: 'rgba(7,16,10,0.55)',
          opacity: isOpen ? 1 : 0,
          pointerEvents: isOpen ? 'auto' : 'none',
          transition: 'opacity 200ms var(--ease-organic)',
          zIndex: 40,
        }}/>

      <div
        role="dialog"
        aria-modal="true"
        aria-label={title}
        style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, top: 60,
          background: '#111D0A',
          borderRadius: '20px 20px 0 0',
          border: '0.5px solid #2D3A22', borderBottom: 'none',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
          transform: isOpen ? 'translateY(0)' : 'translateY(100%)',
          transition: 'transform 240ms var(--ease-organic)',
          zIndex: 41,
          boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
        }}>
        {/* Drag handle */}
        <div style={{ flexShrink: 0, display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
          <span style={{ width: 36, height: 4, background: '#445239', borderRadius: 2 }}/>
        </div>

        {/* Header */}
        <div style={{
          padding: '6px 14px 14px',
          display: 'flex', alignItems: 'center', gap: 6,
          borderBottom: '0.5px solid #1F2B16',
          flexShrink: 0,
        }}>
          <button onClick={onBack} aria-label="Back"
            style={{
              background: 'transparent', border: 'none', padding: 6, color: '#C9D2BB',
              display: 'flex', cursor: 'pointer',
            }}>
            <PIcons.ChevronLeft size={20}/>
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ font: '500 16px var(--font-sans)', color: '#F2EDE4' }}>{title}</div>
            {subtitle && (
              <div style={{ font: 'italic 400 12.5px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
                {subtitle}
              </div>
            )}
          </div>
          <button onClick={onClose} aria-label="Close"
            style={{
              background: 'transparent', border: 'none', padding: 6, color: '#586552',
              display: 'flex', cursor: 'pointer',
            }}>
            <PIcons.X size={18}/>
          </button>
        </div>

        {/* Body — scrolls */}
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
          {children}
        </div>

        {/* Footer — sticky action */}
        {footer && (
          <div style={{
            padding: '12px 16px 18px', borderTop: '0.5px solid #1F2B16',
            flexShrink: 0,
          }}>
            {footer}
          </div>
        )}
      </div>
    </>
  );
}


// ─────────────────────────────────────────────────────────────
// Add to a group — pick an existing group or start a new one.
// ─────────────────────────────────────────────────────────────

function AddToGroupSheet({ user, isOpen, onBack, onClose, onConfirm }) {
  const [selectedId, setSelectedId] = React.useState(null);
  const [phase, setPhase] = React.useState('list');     // 'list' | 'done'
  const [createdId, setCreatedId] = React.useState(null);

  React.useEffect(() => {
    if (isOpen) { setSelectedId(null); setPhase('list'); setCreatedId(null); }
  }, [isOpen, user?.handle]);

  if (!user) return null;

  // Groups that DON'T already contain this user
  const eligible = YOUR_GROUPS.filter(g => !g.members.includes(user.handle));
  const alreadyIn = YOUR_GROUPS.filter(g =>  g.members.includes(user.handle));

  function commit() {
    setPhase('done');
    onConfirm({ groupId: selectedId, user });
    window.setTimeout(() => onBack(), 1400);
  }

  function createNew() {
    const id = `new-${Date.now()}`;
    setCreatedId(id);
    setSelectedId(id);
  }

  return (
    <SecondarySheet
      title={`Add @${user.handle} to a group`}
      subtitle="Groups are small, sealed personal forests."
      isOpen={isOpen}
      onBack={onBack}
      onClose={onClose}
      footer={
        phase === 'done' ? null :
        <button
          disabled={!selectedId}
          onClick={commit}
          style={{
            width: '100%',
            background: selectedId ? '#4F8E51' : '#1A2812',
            color: selectedId ? '#F2EDE4' : '#586552',
            border: 'none', padding: '13px', borderRadius: 12,
            font: '500 14px var(--font-sans)',
            cursor: selectedId ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
          <PIcons.UserPlus size={16} color={selectedId ? '#F2EDE4' : '#586552'}/>
          Add to group
        </button>
      }
    >
      {phase === 'done' ? (
        <DoneBeat
          label={`Added @${user.handle}`}
          subline="They'll be notified in their Sunlight."
        />
      ) : (
        <div style={{ padding: '14px 18px 18px' }}>
          {/* Already in */}
          {alreadyIn.length > 0 && (
            <>
              <SectionLabel>Already in</SectionLabel>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8, marginBottom: 14 }}>
                {alreadyIn.map(g => <GroupRow key={g.id} group={g} disabled label="member"/>)}
              </div>
            </>
          )}

          {/* Pick */}
          <SectionLabel>{eligible.length > 0 ? 'Your groups' : 'No other groups yet'}</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8 }}>
            {eligible.map(g => (
              <GroupRow key={g.id} group={g}
                selected={selectedId === g.id}
                onTap={() => setSelectedId(g.id)}/>
            ))}
            {/* Create new tile */}
            <button onClick={createNew}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '13px 14px',
                background: createdId ? '#3A2A07' : 'transparent',
                border: '0.5px dashed ' + (createdId ? '#6B5018' : '#445239'),
                borderRadius: 10,
                color: createdId ? '#F4DCA0' : '#76AB78',
                font: '500 13.5px var(--font-sans)',
                cursor: 'pointer', textAlign: 'left',
              }}>
              <PIcons.Plus size={16} color={createdId ? '#F4DCA0' : '#76AB78'}/>
              <span style={{ flex: 1 }}>
                {createdId
                  ? `New group with @${user.handle}`
                  : 'Start a new group with @' + user.handle}
              </span>
              {createdId && <PIcons.Check size={16} color="#F4DCA0"/>}
            </button>
          </div>

          <div style={{
            marginTop: 14, padding: 11,
            background: '#0B1306', border: '0.5px solid #1F2B16', borderRadius: 10,
            font: 'italic 400 12px/1.55 var(--font-serif)', color: '#8A9678',
          }}>
            Adding someone to a group makes the group's previous messages visible to them only from this point forward.
          </div>
        </div>
      )}
    </SecondarySheet>
  );
}


function GroupRow({ group, selected, disabled = false, label, onTap }) {
  const others = group.members.slice(0, 3);
  return (
    <button onClick={onTap} disabled={disabled}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '11px 12px',
        background: selected ? 'rgba(79,142,81,0.10)' : '#0B1306',
        border: `0.5px solid ${selected ? '#4F8E51' : '#1F2B16'}`,
        borderRadius: 10, width: '100%', cursor: disabled ? 'default' : 'pointer',
        opacity: disabled ? 0.55 : 1,
        textAlign: 'left',
      }}>
      {/* face stack */}
      <div style={{ display: 'flex', flexShrink: 0, paddingLeft: 6 }}>
        {others.map((h, i) => {
          const u = INITIAL_FOLK.find(f => f.handle === h);
          return (
            <div key={h} style={{
              marginLeft: i === 0 ? 0 : -10,
              border: '1.5px solid #0B1306', borderRadius: '50%',
            }}>
              {u
                ? <FolkAvatar user={u} size={24}/>
                : <div style={{ width: 24, height: 24, borderRadius: '50%',
                                background: '#243319' }}/>}
            </div>
          );
        })}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4' }}>{group.name}</div>
        <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678', marginTop: 2 }}>
          {group.members.length} members · last touch {group.updated}
        </div>
      </div>
      {label && (
        <span style={{
          font: '500 10.5px var(--font-sans)', color: '#586552',
          letterSpacing: '0.04em', textTransform: 'uppercase',
        }}>{label}</span>
      )}
      {selected && !label && <PIcons.Check size={16} color="#76AB78"/>}
    </button>
  );
}


// ─────────────────────────────────────────────────────────────
// Invite to a forest — list your forests, mark which ones the
// target is already in / which ones you can invite them to.
// Invite-only forests gate the invite button behind the user's
// referral allowance.
// ─────────────────────────────────────────────────────────────

function InviteToForestSheet({ user, isOpen, onBack, onClose, onConfirm }) {
  const [selectedIds, setSelectedIds] = React.useState(new Set());
  const [phase, setPhase] = React.useState('list');

  React.useEffect(() => {
    if (isOpen) { setSelectedIds(new Set()); setPhase('list'); }
  }, [isOpen, user?.handle]);

  if (!user) return null;

  const already = USER_IN_FORESTS[user.handle] || [];
  function toggle(id) {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }
  function commit() {
    setPhase('done');
    onConfirm({ forestIds: [...selectedIds], user });
    window.setTimeout(() => onBack(), 1400);
  }

  return (
    <SecondarySheet
      title={`Invite @${user.handle} to a forest`}
      subtitle="Open forests anyone can join. Invite-only forests need a referral from you."
      isOpen={isOpen}
      onBack={onBack}
      onClose={onClose}
      footer={
        phase === 'done' ? null :
        <button
          disabled={selectedIds.size === 0}
          onClick={commit}
          style={{
            width: '100%',
            background: selectedIds.size > 0 ? '#4F8E51' : '#1A2812',
            color: selectedIds.size > 0 ? '#F2EDE4' : '#586552',
            border: 'none', padding: '13px', borderRadius: 12,
            font: '500 14px var(--font-sans)',
            cursor: selectedIds.size > 0 ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
          <PIcons.Tree size={16} color={selectedIds.size > 0 ? '#F2EDE4' : '#586552'}/>
          {selectedIds.size <= 1 ? 'Send invitation' : `Send ${selectedIds.size} invitations`}
        </button>
      }
    >
      {phase === 'done' ? (
        <DoneBeat
          label={selectedIds.size <= 1 ? `Invitation sent` : `${selectedIds.size} invitations sent`}
          subline={`@${user.handle} will see this in their Sunlight.`}
        />
      ) : (
        <div style={{ padding: '14px 18px 18px',
                      display: 'flex', flexDirection: 'column', gap: 10 }}>
          {YOUR_FORESTS.map(f => {
            const isMember = already.includes(f.id);
            const isSelected = selectedIds.has(f.id);
            return (
              <ForestRow key={f.id} forest={f}
                disabled={isMember}
                selected={isSelected}
                onTap={() => !isMember && toggle(f.id)}
                memberLabel={isMember ? 'already in' : null}/>
            );
          })}

          <div style={{
            marginTop: 4, padding: 11,
            background: '#0B1306', border: '0.5px solid #1F2B16', borderRadius: 10,
            font: 'italic 400 12px/1.55 var(--font-serif)', color: '#8A9678',
          }}>
            An invitation to an invite-only forest counts as your referral. You have 3 referrals left this month.
          </div>
        </div>
      )}
    </SecondarySheet>
  );
}


function ForestRow({ forest, selected, disabled, memberLabel, onTap }) {
  const kindColor = { city: '#76AB78', campus: '#A8C5A0', interest: '#D6BFA8' }[forest.kind] || '#76AB78';
  return (
    <button onClick={onTap} disabled={disabled}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 14px',
        background: selected ? 'rgba(79,142,81,0.10)' : '#0B1306',
        border: `0.5px solid ${selected ? '#4F8E51' : '#1F2B16'}`,
        borderRadius: 12, width: '100%',
        cursor: disabled ? 'default' : 'pointer',
        opacity: disabled ? 0.5 : 1,
        textAlign: 'left',
      }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: '#1A2812', border: '0.5px solid #2D3A22',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <FLIcons.TreeMark size={26} active={!disabled}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ font: '500 14px var(--font-sans)', color: '#F2EDE4',
                         whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                         minWidth: 0, maxWidth: '100%' }}>{forest.name}</span>
          <span style={{
            font: '500 9px var(--font-sans)', color: kindColor,
            background: '#1A2812', padding: '1px 6px', borderRadius: 999,
            textTransform: 'lowercase', whiteSpace: 'nowrap', flexShrink: 0,
          }}>{forest.kind}</span>
          {forest.openness === 'invite' && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 3,
              font: '500 9px var(--font-sans)', color: '#F4DCA0',
              background: '#3A2A07', padding: '1px 6px 1px 5px', borderRadius: 999,
              whiteSpace: 'nowrap', flexShrink: 0,
            }}>
              <PIcons.Lock size={9} color="#F4DCA0"/>invite-only
            </span>
          )}
        </div>
        <div style={{ font: '400 11.5px var(--font-sans)', color: '#8A9678', marginTop: 2,
                      whiteSpace: 'nowrap' }}>
          {forest.members} members
        </div>
      </div>
      {memberLabel ? (
        <span style={{
          font: '500 10.5px var(--font-sans)', color: '#586552',
          letterSpacing: '0.04em', textTransform: 'uppercase',
          whiteSpace: 'nowrap', flexShrink: 0,
        }}>{memberLabel}</span>
      ) : selected ? (
        <span style={{
          width: 20, height: 20, borderRadius: '50%',
          background: '#4F8E51',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <PIcons.Check size={12} color="#F2EDE4"/>
        </span>
      ) : (
        <span style={{
          width: 20, height: 20, borderRadius: '50%',
          border: '1px solid #445239', flexShrink: 0,
        }}/>
      )}
    </button>
  );
}


// ─────────────────────────────────────────────────────────────
// Shared completion beat used by both sheets.
// ─────────────────────────────────────────────────────────────

function DoneBeat({ label, subline }) {
  return (
    <div style={{
      flex: 1, padding: '50px 24px 32px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      textAlign: 'center', gap: 12,
    }}>
      <div style={{ position: 'relative', width: 76, height: 76, marginBottom: 4 }}>
        <span style={{ position: 'absolute', inset: 0, borderRadius: '50%',
                       border: '1px solid rgba(79,142,81,0.55)',
                       animation: 'sunPulse 1.4s var(--ease-organic) infinite' }}/>
        <span style={{
          position: 'absolute', inset: 22, borderRadius: '50%',
          background: '#4F8E51',
          boxShadow: '0 0 18px rgba(79,142,81,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <PIcons.Check size={18} color="#F2EDE4"/>
        </span>
      </div>
      <div style={{ font: '500 17px var(--font-mono)', color: '#F2EDE4' }}>{label}</div>
      <div style={{ font: 'italic 400 13px/1.55 var(--font-serif)', color: '#A8C5A0', maxWidth: 240 }}>
        {subline}
      </div>
    </div>
  );
}


window.AddToGroupSheet     = AddToGroupSheet;
window.InviteToForestSheet = InviteToForestSheet;
