// You tab — reflects single-huddle reality
//   - Not in huddle: offers Join or Create (Create disabled when already in one)
//   - In huddle:     shows current huddle with members + leave

function YouScreen({ inHuddle, huddle, email, onJoin, onCreate, onSignOut }) {
  const { state, actions } = useStore();
  const me = state.user;
  const ownerId = huddle?.ownerId;
  const isOwner = me && ownerId === me.id;
  const [sheet, setSheet] = React.useState(null);  // 'profile' | 'editHuddle' | 'notifications' | 'addToHome' | 'privacy' | 'transfer' | 'deleteHuddle'
  const closeSheet = () => setSheet(null);

  const attemptLeave = async () => {
    try {
      const r = await actions.tryLeaveHuddle();
      if (r.needsTransfer) setSheet('transfer');
      else if (r.needsDelete) setSheet('deleteHuddle');
    } catch (e) { alert(e.message || 'leave failed'); }
  };

  return (
    <Screen>
      {inHuddle && huddle && <GroupBar group={huddle} members={huddle.members}/>}
      {!inHuddle && (
        <div style={{ padding: 'calc(env(safe-area-inset-top, 12px) + 18px) 20px 0', height: 46 }}/>
      )}
      <HuddleHeader title="You"/>

      <div style={{ padding: '0 16px' }}>
        {/* Profile card */}
        <button onClick={() => setSheet('profile')} style={{
          background: C.white, borderRadius: 20, padding: 18,
          display: 'flex', alignItems: 'center', gap: 14,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
          border: 'none', width: '100%', cursor: 'pointer', textAlign: 'left',
        }}>
          <Avatar user={me || { avatar: '?', color: C.coral }} size={52}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
              fontSize: 26, color: C.navy, lineHeight: 1,
            }}>{me?.name || 'You'}</div>
            <div style={{
              fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted,
              marginTop: 4,
            }}>{email || 'you@gmail.com'}</div>
          </div>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M10 3l3 3-7 7H3v-3z M9 4l3 3" stroke={C.navy} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>

        {/* Section label */}
        <div style={{
          padding: '22px 4px 10px',
          fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700,
          color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase',
        }}>Your flock</div>

        {inHuddle && huddle ? (
          <InHuddleCard
            huddle={huddle}
            isOwner={isOwner}
            onLeave={attemptLeave}
            onEditHuddle={() => setSheet('editHuddle')}
          />
        ) : (
          <NoHuddleActions onJoin={onJoin} onCreate={onCreate}/>
        )}

        {/* Settings / misc */}
        <div style={{
          padding: '22px 4px 10px',
          fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700,
          color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase',
        }}>Settings</div>
        <div style={{
          background: C.white, borderRadius: 18, overflow: 'hidden',
          boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
        }}>
          {[
            { icon: '🔔', label: 'Notifications', detail: notifLabel(state.prefs?.notifications), onClick: () => setSheet('notifications') },
            { icon: '📲', label: 'Add to Home Screen', detail: 'How-to', onClick: () => setSheet('addToHome') },
            { icon: '🔒', label: 'Privacy & data', onClick: () => setSheet('privacy') },
            { icon: '🚪', label: 'Sign out', danger: true, onClick: onSignOut },
          ].map((row, i, arr) => (
            <div key={i} onClick={row.onClick} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '13px 16px',
              borderBottom: i < arr.length - 1 ? `1px solid ${C.hairline}` : 'none',
              cursor: 'pointer',
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8,
                background: row.danger ? 'rgba(255,107,91,0.1)' : C.cream,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14,
              }}>{row.icon}</div>
              <div style={{
                flex: 1, fontFamily: '"DM Sans",system-ui', fontSize: 14.5,
                color: row.danger ? C.coral : C.navy, fontWeight: row.danger ? 600 : 500,
              }}>{row.label}</div>
              {row.detail && (
                <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted }}>
                  {row.detail}
                </div>
              )}
              {!row.danger && (
                <svg width="7" height="12" viewBox="0 0 7 12" style={{ color: C.inkMuted, opacity: 0.5 }}>
                  <path d="M1 1l5 5-5 5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </div>
          ))}
        </div>
      </div>

      {sheet === 'profile'       && <ProfileSheet me={me} email={email} actions={actions} onClose={closeSheet}/>}
      {sheet === 'editHuddle'    && <EditHuddleSheet huddle={huddle} actions={actions} onClose={closeSheet} onRequestTransfer={() => setSheet('transfer')} onRequestDelete={() => setSheet('deleteHuddle')}/>}
      {sheet === 'notifications' && <NotificationsSheet value={state.prefs?.notifications || 'everything'} actions={actions} onClose={closeSheet}/>}
      {sheet === 'addToHome'     && <AddToHomeSheet onClose={closeSheet}/>}
      {sheet === 'privacy'       && <PrivacySheet email={email} actions={actions} onClose={closeSheet}/>}
      {sheet === 'transfer'      && <TransferOwnershipSheet huddle={huddle} me={me} actions={actions} onClose={closeSheet} leaveAfter/>}
      {sheet === 'deleteHuddle'  && <DeleteHuddleSheet huddle={huddle} actions={actions} onClose={closeSheet}/>}
    </Screen>
  );
}

function notifLabel(pref) {
  return { everything: 'Everything', mentions: 'Mentions only', off: 'Off' }[pref] || 'Everything';
}

function InHuddleCard({ huddle, isOwner, onLeave, onEditHuddle }) {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    let ok = false;
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(huddle.code);
        ok = true;
      }
    } catch (e) { /* fall through to execCommand */ }
    if (!ok) {
      try {
        const ta = document.createElement('textarea');
        ta.value = huddle.code;
        ta.style.position = 'fixed'; ta.style.opacity = '0';
        document.body.appendChild(ta); ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
      } catch (e2) {}
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };
  return (
    <div style={{
      background: C.white, borderRadius: 20, padding: 18,
      boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 52, height: 52, borderRadius: 14,
          background: C.coralSoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 26,
        }}>{huddle.emoji}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
            fontSize: 24, color: C.navy, lineHeight: 1.1,
          }}>{huddle.name}</div>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 13,
            color: C.inkMuted, marginTop: 3,
          }}>
            {huddle.members.length} {huddle.members.length === 1 ? 'member' : 'members'}
            {isOwner && <span style={{ color: C.coralDeep }}> · you own it</span>}
          </div>
        </div>
        {isOwner && (
          <button onClick={onEditHuddle} style={{
            width: 36, height: 36, borderRadius: 18,
            background: C.cream, border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 0, flexShrink: 0,
          }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M10 3l3 3-7 7H3v-3z M9 4l3 3" stroke={C.navy} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        )}
      </div>

      {/* Members */}
      <div style={{ marginTop: 16 }}>
        <div style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 11, fontWeight: 700,
          color: C.inkMuted, letterSpacing: 0.8, textTransform: 'uppercase',
          marginBottom: 8,
        }}>Members</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {huddle.members.map(u => (
            <div key={u.id} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              background: C.cream, padding: '5px 11px 5px 5px', borderRadius: 999,
            }}>
              <Avatar user={u} size={22}/>
              <span style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, fontWeight: 600, color: C.navy }}>
                {u.name}
              </span>
            </div>
          ))}
          <button onClick={copy} style={{
            display: 'inline-flex', alignItems: 'center', gap: 7,
            background: 'rgba(255,107,91,0.08)',
            border: `1.2px dashed ${C.coral}`,
            padding: '5px 12px', borderRadius: 999, color: C.coral,
            fontFamily: '"DM Sans",system-ui', fontSize: 12.5, fontWeight: 600,
            cursor: 'pointer',
          }}>
            {copied ? '✓ Code copied' : '+ Invite'}
          </button>
        </div>
      </div>

      {/* Invite code */}
      <div style={{
        marginTop: 16, padding: 12,
        background: C.cream, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 11, fontWeight: 700,
            color: C.inkMuted, letterSpacing: 0.8, textTransform: 'uppercase',
          }}>Invite code</div>
          <div style={{
            fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
            fontSize: 22, color: C.navy, letterSpacing: 0.5, marginTop: 2,
          }}>{huddle.code}</div>
        </div>
        <button onClick={copy} style={{
          height: 36, padding: '0 14px', borderRadius: 999,
          background: copied ? C.sage : C.navy, color: C.cream, border: 'none',
          fontFamily: '"DM Sans",system-ui', fontSize: 13, fontWeight: 600,
          cursor: 'pointer', transition: 'background 200ms ease',
        }}>{copied ? 'Copied' : 'Copy'}</button>
      </div>

      {/* Leave */}
      <button onClick={onLeave} style={{
        marginTop: 14, width: '100%', height: 44, borderRadius: 999,
        background: 'transparent',
        border: `1.5px solid rgba(255,107,91,0.35)`,
        color: C.coral,
        fontFamily: '"DM Sans",system-ui', fontSize: 14, fontWeight: 600,
        cursor: 'pointer',
      }}>Leave flock</button>
    </div>
  );
}

function NoHuddleActions({ onJoin, onCreate }) {
  return (
    <div>
      <div style={{
        fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.inkMuted,
        lineHeight: 1.45, padding: '0 4px 14px', letterSpacing: -0.05,
      }}>
        you're not in a flock yet. join one with a code from a friend, or start fresh.
      </div>

      {/* Join — primary */}
      <button onClick={onJoin} style={{
        display: 'flex', alignItems: 'center', gap: 14,
        width: '100%', padding: 16, marginBottom: 10,
        background: C.white, borderRadius: 18,
        border: 'none', cursor: 'pointer', textAlign: 'left',
        boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
      }}>
        <div style={{
          width: 46, height: 46, borderRadius: 14,
          background: C.coralSoft, color: C.coral,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M4 12l6 6L19 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
            fontSize: 22, color: C.navy, letterSpacing: -0.3,
          }}>Join a flock</div>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted,
            marginTop: 2,
          }}>got an invite code from a friend? paste it in.</div>
        </div>
        <svg width="8" height="14" viewBox="0 0 8 14" style={{ color: C.inkMuted, opacity: 0.5, flexShrink: 0 }}>
          <path d="M1 1l6 6-6 6" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>

      {/* Create — secondary (same card style) */}
      <button onClick={onCreate} style={{
        display: 'flex', alignItems: 'center', gap: 14,
        width: '100%', padding: 16,
        background: C.white, borderRadius: 18,
        border: 'none', cursor: 'pointer', textAlign: 'left',
        boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
      }}>
        <div style={{
          width: 46, height: 46, borderRadius: 14,
          background: 'rgba(138,168,150,0.2)', color: C.sage,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M11 4v14M4 11h14" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
          </svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
            fontSize: 22, color: C.navy, letterSpacing: -0.3,
          }}>Create a flock</div>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted,
            marginTop: 2,
          }}>name it, invite your people, start planning.</div>
        </div>
        <svg width="8" height="14" viewBox="0 0 8 14" style={{ color: C.inkMuted, opacity: 0.5, flexShrink: 0 }}>
          <path d="M1 1l6 6-6 6" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>

      {/* Mutex note */}
      <div style={{
        marginTop: 12, padding: '10px 12px',
        background: 'rgba(30,42,74,0.05)', borderRadius: 12,
        display: 'flex', alignItems: 'flex-start', gap: 8,
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, marginTop: 1 }}>
          <circle cx="7" cy="7" r="6" stroke={C.inkMuted} strokeWidth="1.3"/>
          <path d="M7 4v3.5M7 10v0.5" stroke={C.inkMuted} strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
        <div style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted,
          lineHeight: 1.4, letterSpacing: -0.05,
        }}>
          You can only be in one flock at a time. You'll need to leave your current one before creating a new flock.
        </div>
      </div>
    </div>
  );
}

// ─── Join flow screen ───
function JoinHuddleScreen({ onBack, onJoined }) {
  const [code, setCode] = React.useState('');
  return (
    <Screen>
      <div style={{
        padding: 'calc(env(safe-area-inset-top, 12px) + 18px) 16px 10px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 'none',
          color: C.inkMuted, fontFamily: '"DM Sans",system-ui',
          fontSize: 15, fontWeight: 500, cursor: 'pointer', padding: 4,
        }}>Cancel</button>
        <div style={{ fontFamily: '"DM Sans", system-ui', fontSize: 15, fontWeight: 600, color: C.navy }}>
          Join a flock
        </div>
        <div style={{ width: 54 }}/>
      </div>
      <div style={{ padding: '20px 20px 0' }}>
        <h1 style={{
          margin: 0,
          fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
          fontSize: 34, color: C.navy, letterSpacing: -0.6, lineHeight: 1.05,
          fontWeight: 400,
        }}>enter invite code</h1>
        <div style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.inkMuted,
          marginTop: 6, lineHeight: 1.45,
        }}>ask a friend already in the flock to share theirs.</div>

        <div style={{
          marginTop: 24, background: C.white, borderRadius: 14,
          padding: '16px 16px', boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
        }}>
          <input
            value={code}
            onChange={e => setCode(e.target.value.toUpperCase())}
            placeholder="SUN-PALM-42"
            style={{
              width: '100%', border: 'none', background: 'transparent', outline: 'none',
              fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
              fontSize: 28, color: C.navy, letterSpacing: 1,
              textAlign: 'center',
            }}
          />
        </div>

        <button
          disabled={code.length < 4}
          onClick={() => onJoined && onJoined(code)}
          style={{
            width: '100%', marginTop: 20, height: 54, borderRadius: 999,
            border: 'none',
            background: code.length >= 4
              ? `linear-gradient(180deg, ${C.coral}, ${C.coralDeep})`
              : 'rgba(30,42,74,0.1)',
            color: code.length >= 4 ? '#fff' : C.inkMuted,
            fontFamily: '"DM Sans",system-ui',
            fontWeight: 700, fontSize: 16,
            cursor: code.length >= 4 ? 'pointer' : 'default',
            boxShadow: code.length >= 4 ? '0 6px 18px rgba(255,107,91,0.4)' : 'none',
          }}>Join flock</button>
      </div>
    </Screen>
  );
}

// ─── Create flow screen ───
function CreateHuddleScreen({ onBack, onCreated }) {
  const [name, setName] = React.useState('');
  const [emoji, setEmoji] = React.useState('🌴');
  const emojis = ['🌴','🏕️','🎉','☕','🍕','🎨','🏔️','🌮','🎸','🌊'];
  return (
    <Screen>
      <div style={{
        padding: 'calc(env(safe-area-inset-top, 12px) + 18px) 16px 10px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 'none',
          color: C.inkMuted, fontFamily: '"DM Sans",system-ui',
          fontSize: 15, fontWeight: 500, cursor: 'pointer', padding: 4,
        }}>Cancel</button>
        <div style={{ fontFamily: '"DM Sans", system-ui', fontSize: 15, fontWeight: 600, color: C.navy }}>
          Create a flock
        </div>
        <div style={{ width: 54 }}/>
      </div>

      <div style={{ padding: '20px 20px 0' }}>
        <h1 style={{
          margin: 0,
          fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
          fontSize: 34, color: C.navy, letterSpacing: -0.6, lineHeight: 1.05,
          fontWeight: 400,
        }}>name your flock</h1>

        {/* Emoji + name */}
        <div style={{
          marginTop: 22, background: C.white, borderRadius: 18, padding: 16,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 54, height: 54, borderRadius: 14,
              background: C.coralSoft,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 28, flexShrink: 0,
            }}>{emoji}</div>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="Weekend Crew"
              style={{
                flex: 1, border: 'none', background: 'transparent', outline: 'none',
                fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
                fontSize: 26, color: C.navy, letterSpacing: -0.3,
                padding: '6px 0',
                minWidth: 0,
              }}
            />
          </div>
          <div style={{ marginTop: 14 }}>
            <div style={{
              fontFamily: '"DM Sans",system-ui', fontSize: 11, fontWeight: 700,
              color: C.inkMuted, letterSpacing: 0.8, textTransform: 'uppercase',
              marginBottom: 8,
            }}>pick an emoji</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {emojis.map(e => (
                <button key={e} onClick={() => setEmoji(e)} style={{
                  width: 38, height: 38, borderRadius: 10,
                  border: emoji === e ? `1.5px solid ${C.coral}` : '1.5px solid transparent',
                  background: emoji === e ? 'rgba(255,107,91,0.08)' : C.cream,
                  fontSize: 20, cursor: 'pointer', padding: 0,
                }}>{e}</button>
              ))}
            </div>
          </div>
        </div>

        <div style={{
          marginTop: 14, padding: '10px 12px',
          background: 'rgba(138,168,150,0.14)', borderRadius: 12,
          display: 'flex', alignItems: 'flex-start', gap: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, marginTop: 1 }}>
            <circle cx="7" cy="7" r="6" fill={C.sage}/>
            <path d="M4.2 7.2l2 2 3.6-4" stroke="#fff" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <div style={{
            fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.sage,
            lineHeight: 1.4, letterSpacing: -0.05, fontWeight: 600,
          }}>
            You'll get a shareable invite code as soon as your flock is created.
          </div>
        </div>

        <button
          disabled={name.length < 2}
          onClick={() => onCreated && onCreated(name.trim(), emoji)}
          style={{
            width: '100%', marginTop: 20, height: 54, borderRadius: 999,
            border: 'none',
            background: name.length >= 2
              ? `linear-gradient(180deg, ${C.coral}, ${C.coralDeep})`
              : 'rgba(30,42,74,0.1)',
            color: name.length >= 2 ? '#fff' : C.inkMuted,
            fontFamily: '"DM Sans",system-ui',
            fontWeight: 700, fontSize: 16,
            cursor: name.length >= 2 ? 'pointer' : 'default',
            boxShadow: name.length >= 2 ? '0 6px 18px rgba(255,107,91,0.4)' : 'none',
          }}>Create flock</button>
      </div>
    </Screen>
  );
}

// ─── Sheets ──────────────────────────────────────────────────────────────
// Generic bottom sheet — dimmed backdrop + rounded panel that slides in.
function BottomSheet({ title, children, onClose, cta, ctaDisabled, ctaLoading }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 80,
      background: 'rgba(30,42,74,0.55)',
      display: 'flex', alignItems: 'flex-end',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: C.cream, width: '100%', maxWidth: 440, margin: '0 auto',
        borderRadius: '24px 24px 0 0',
        padding: '18px 18px calc(env(safe-area-inset-bottom, 0px) + 24px)',
        boxShadow: '0 -8px 40px rgba(30,42,74,0.25)',
        maxHeight: '90dvh', overflow: 'auto',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, margin: '0 auto 14px', background: 'rgba(30,42,74,0.15)' }}/>
        {title && (
          <div style={{ fontFamily: '"Instrument Serif",serif', fontStyle: 'italic', fontSize: 26, color: C.navy, letterSpacing: -0.3, marginBottom: 6 }}>
            {title}
          </div>
        )}
        {children}
        {cta && (
          <button onClick={cta.onClick} disabled={ctaDisabled || ctaLoading} style={{
            width: '100%', marginTop: 18, height: 52, borderRadius: 999, border: 'none',
            background: ctaDisabled ? 'rgba(30,42,74,0.1)' : (cta.danger ? `linear-gradient(180deg, ${C.coral}, ${C.coralDeep})` : C.navy),
            color: ctaDisabled ? C.inkMuted : '#fff',
            fontFamily: '"DM Sans",system-ui', fontWeight: 700, fontSize: 15,
            cursor: ctaDisabled ? 'default' : 'pointer',
            boxShadow: ctaDisabled ? 'none' : '0 6px 18px rgba(30,42,74,0.25)',
          }}>{ctaLoading ? '…' : cta.label}</button>
        )}
        <button onClick={onClose} style={{
          width: '100%', marginTop: 8, height: 44, borderRadius: 999, border: 'none',
          background: 'transparent', color: C.inkMuted,
          fontFamily: '"DM Sans",system-ui', fontWeight: 600, fontSize: 14,
          cursor: 'pointer',
        }}>Cancel</button>
      </div>
    </div>
  );
}

// Profile editor — change display name + upload avatar + "use initial" fallback
function ProfileSheet({ me, email, actions, onClose }) {
  const [name, setName] = React.useState(me?.name || 'You');
  const [avatarUrl, setAvatarUrl] = React.useState(me?.avatarUrl || null);
  const [busy, setBusy] = React.useState(false);
  const libraryRef = React.useRef(null);
  const cameraRef = React.useRef(null);

  const onPick = async (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setBusy(true);
    try {
      const url = await actions.uploadAvatar(f);
      setAvatarUrl(url);
    } catch (err) { alert(err.message || 'upload failed'); }
    finally { setBusy(false); }
  };

  const save = async () => {
    setBusy(true);
    try {
      await actions.updateProfile({ name, avatarUrl });
      onClose();
    } catch (err) { alert(err.message || 'save failed'); }
    finally { setBusy(false); }
  };

  const useInitial = async () => {
    setBusy(true);
    try {
      await actions.updateProfile({ name, avatarUrl: null });
      setAvatarUrl(null);
    } finally { setBusy(false); }
  };

  const display = { name, avatar: (name || '?').trim()[0]?.toUpperCase() || '?', color: me?.color || C.coral, avatarUrl };

  return (
    <BottomSheet title="your profile" onClose={onClose} cta={{ label: 'Save', onClick: save }} ctaLoading={busy}>
      <div style={{ textAlign: 'center', padding: '6px 0 14px' }}>
        <div style={{ position: 'relative', display: 'inline-block' }}>
          <Avatar user={display} size={96}/>
          <div style={{
            position: 'absolute', bottom: -2, right: -2,
            width: 34, height: 34, borderRadius: 17, background: C.coral,
            border: `3px solid ${C.cream}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <rect x="2" y="4" width="12" height="10" rx="2" stroke="#fff" strokeWidth="1.5"/>
              <circle cx="8" cy="9" r="2.5" stroke="#fff" strokeWidth="1.5"/>
            </svg>
          </div>
        </div>
      </div>

      <input ref={libraryRef} type="file" accept="image/*" onChange={onPick} style={{ display: 'none' }}/>
      <input ref={cameraRef} type="file" accept="image/*" capture="user" onChange={onPick} style={{ display: 'none' }}/>

      <div style={{ background: C.white, borderRadius: 16, overflow: 'hidden' }}>
        <SheetRow icon="🖼️" label="Choose from library"   onClick={() => libraryRef.current?.click()}/>
        <SheetRow icon="📷" label="Take a photo"          onClick={() => cameraRef.current?.click()} divider/>
        <SheetRow icon="✦"  label="Use initial"           hint="first letter, coral bg" onClick={useInitial}/>
      </div>

      <div style={{ padding: '14px 4px 6px', fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700, color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase' }}>
        display name
      </div>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
        style={{
          width: '100%', background: C.white, border: 'none', borderRadius: 14,
          padding: '14px 16px', outline: 'none', boxSizing: 'border-box',
          fontFamily: '"DM Sans",system-ui', fontSize: 15, color: C.navy, fontWeight: 500,
          boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
        }}
      />
      <div style={{ padding: '10px 4px 0', fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted }}>
        {email || ''}
      </div>
    </BottomSheet>
  );
}

function SheetRow({ icon, label, hint, onClick, divider, danger }) {
  return (
    <div onClick={onClick} style={{
      padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'pointer',
      borderBottom: divider ? '1px solid rgba(30,42,74,0.06)' : 'none',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 10,
        background: danger ? 'rgba(255,107,91,0.12)' : C.cream,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 15,
      }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14.5, fontWeight: 500, color: danger ? C.coral : C.navy }}>{label}</div>
        {hint && <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted, marginTop: 1 }}>{hint}</div>}
      </div>
      <svg width="7" height="12" viewBox="0 0 7 12" style={{ color: C.inkMuted, opacity: 0.5 }}>
        <path d="M1 1l5 5-5 5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </div>
  );
}

// Owner: rename huddle + change emoji + transfer / delete controls
function EditHuddleSheet({ huddle, actions, onClose, onRequestTransfer, onRequestDelete }) {
  const [name, setName] = React.useState(huddle.name);
  const [emoji, setEmoji] = React.useState(huddle.emoji);
  const [busy, setBusy] = React.useState(false);
  const emojis = ['🌴','🏕️','🎉','☕','🍕','🎨','🏔️','🌮','🎸','🌊','🏀','🎬'];
  const canSave = name.trim().length >= 2 && (name !== huddle.name || emoji !== huddle.emoji);
  const save = async () => {
    setBusy(true);
    try { await actions.renameHuddle({ name: name.trim(), emoji }); onClose(); }
    catch (e) { alert(e.message || 'save failed'); }
    finally { setBusy(false); }
  };
  return (
    <BottomSheet title="edit flock" onClose={onClose} cta={{ label: 'Save', onClick: save }} ctaDisabled={!canSave} ctaLoading={busy}>
      <div style={{ textAlign: 'center', padding: '6px 0 16px' }}>
        <div style={{
          width: 84, height: 84, borderRadius: 22, background: C.coralSoft,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 40,
        }}>{emoji}</div>
        <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 11, color: C.inkMuted, marginTop: 10 }}>pick an emoji</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8, justifyContent: 'center' }}>
          {emojis.map(e => (
            <button key={e} onClick={() => setEmoji(e)} style={{
              width: 40, height: 40, borderRadius: 10,
              border: emoji === e ? `1.5px solid ${C.coral}` : '1.5px solid transparent',
              background: emoji === e ? 'rgba(255,107,91,0.08)' : C.cream,
              fontSize: 22, cursor: 'pointer', padding: 0,
            }}>{e}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '4px 4px 8px', fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700, color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase' }}>
        flock name
      </div>
      <div style={{ background: C.white, borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, boxShadow: '0 1px 3px rgba(30,42,74,0.04)' }}>
        <input
          value={name}
          onChange={e => setName(e.target.value)}
          style={{
            flex: 1, border: 'none', background: 'transparent', outline: 'none',
            fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
            fontSize: 22, color: C.navy, minWidth: 0,
          }}
        />
        <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 11, color: C.inkMuted }}>
          {name.length}/40
        </div>
      </div>

      <div style={{ padding: '20px 4px 6px', fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700, color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase' }}>
        owner controls
      </div>
      <div style={{ background: C.white, borderRadius: 14, overflow: 'hidden' }}>
        <SheetRow icon="↗︎" label="Transfer ownership" hint="hand off to another member" onClick={() => { onClose(); onRequestTransfer(); }} divider/>
        <SheetRow icon="🗑"  label="Delete flock" danger onClick={() => { onClose(); onRequestDelete(); }}/>
      </div>
    </BottomSheet>
  );
}

// Ownership transfer — picks a member to become the new owner.
// If `leaveAfter` is true, the caller also leaves the huddle after transferring.
function TransferOwnershipSheet({ huddle, me, actions, onClose, leaveAfter = false }) {
  const candidates = huddle.members.filter(m => m.id !== me?.id);
  const [selected, setSelected] = React.useState(candidates[0]?.id || null);
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    if (!selected) return;
    setBusy(true);
    try { await actions.transferOwnership(selected, leaveAfter); onClose(); }
    catch (e) { alert(e.message || 'transfer failed'); }
    finally { setBusy(false); }
  };
  const targetName = candidates.find(c => c.id === selected)?.name || '';
  return (
    <BottomSheet title="hand off the flock first" onClose={onClose}
      cta={{ label: leaveAfter ? `Transfer to ${targetName} & leave` : `Transfer to ${targetName}`, onClick: submit, danger: true }}
      ctaDisabled={!selected} ctaLoading={busy}>
      <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.inkMuted, lineHeight: 1.5, marginBottom: 14 }}>
        {leaveAfter
          ? <>you're the owner of <b>{huddle.name}</b>. pick someone to take over before you go — otherwise the flock has no one keeping the lights on.</>
          : <>pick a member to become the new owner.</>}
      </div>
      <div style={{ padding: '0 4px 6px', fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700, color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase' }}>
        transfer to
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {candidates.length === 0 && (
          <div style={{ padding: 14, textAlign: 'center', fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted }}>
            No other members — invite someone first.
          </div>
        )}
        {candidates.map(m => {
          const on = m.id === selected;
          return (
            <button key={m.id} onClick={() => setSelected(m.id)} style={{
              background: C.white,
              border: on ? `2px solid ${C.coral}` : '2px solid transparent',
              borderRadius: 14, padding: '10px 12px', display: 'flex', gap: 12, alignItems: 'center',
              cursor: 'pointer', textAlign: 'left',
            }}>
              <Avatar user={m} size={36}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: '"DM Sans",system-ui', fontWeight: 600, fontSize: 14 }}>{m.name}</div>
              </div>
              {on && (
                <svg width="18" height="18" viewBox="0 0 16 16">
                  <circle cx="8" cy="8" r="7" fill={C.coral}/>
                  <path d="M5 8l2 2 4-5" stroke="#fff" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </button>
          );
        })}
      </div>
    </BottomSheet>
  );
}

function DeleteHuddleSheet({ huddle, actions, onClose }) {
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    setBusy(true);
    try { await actions.deleteHuddle(); onClose(); }
    catch (e) { alert(e.message || 'delete failed'); }
    finally { setBusy(false); }
  };
  return (
    <BottomSheet title={`delete ${huddle.name}?`} onClose={onClose}
      cta={{ label: 'Delete flock', onClick: submit, danger: true }} ctaLoading={busy}>
      <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.inkMuted, lineHeight: 1.5 }}>
        you're the only member, so leaving = deleting. all items and chats in this flock will be gone. this can't be undone.
      </div>
      <div style={{ marginTop: 14, padding: 12, background: 'rgba(255,107,91,0.08)', borderRadius: 12, fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.coralDeep, fontWeight: 600, lineHeight: 1.4 }}>
        want to keep it alive? invite a friend first, then transfer ownership.
      </div>
    </BottomSheet>
  );
}

function NotificationsSheet({ value, actions, onClose }) {
  const [picked, setPicked] = React.useState(value);
  const [busy, setBusy] = React.useState(false);
  const save = async () => {
    setBusy(true);
    try { await actions.setNotifications(picked); onClose(); }
    catch (e) { alert(e.message || 'could not save'); }
    finally { setBusy(false); }
  };
  const options = [
    { id: 'everything', label: 'Everything',     hint: 'every new item, vote, and comment' },
    { id: 'mentions',   label: 'Mentions only',  hint: 'when you\'re @-mentioned or voted up' },
    { id: 'off',        label: 'Off',            hint: 'no pings — check in when you want' },
  ];
  return (
    <BottomSheet title="notifications" onClose={onClose}
      cta={{ label: 'Save', onClick: save }} ctaLoading={busy} ctaDisabled={picked === value}>
      <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted, marginBottom: 14, lineHeight: 1.5 }}>
        pick how loud this flock should be.
      </div>
      <div style={{ background: C.white, borderRadius: 16, overflow: 'hidden' }}>
        {options.map((o, i) => (
          <label key={o.id} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', cursor: 'pointer',
            borderBottom: i < options.length - 1 ? '1px solid rgba(30,42,74,0.06)' : 'none',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%',
              border: `1.8px solid ${picked === o.id ? C.coral : 'rgba(30,42,74,0.25)'}`,
              background: picked === o.id ? C.coral : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {picked === o.id && <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff' }}/>}
            </div>
            <input type="radio" checked={picked === o.id} onChange={() => setPicked(o.id)} style={{ display: 'none' }}/>
            <div style={{ flex: 1 }} onClick={() => setPicked(o.id)}>
              <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14.5, fontWeight: 600, color: C.navy }}>{o.label}</div>
              <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted, marginTop: 1 }}>{o.hint}</div>
            </div>
          </label>
        ))}
      </div>
    </BottomSheet>
  );
}

function AddToHomeSheet({ onClose }) {
  // Detect environment to show the right instructions
  const ua = navigator.userAgent || '';
  const isIOS = /iPad|iPhone|iPod/.test(ua);
  const isAndroid = /Android/.test(ua);
  const isStandalone = (window.matchMedia?.('(display-mode: standalone)').matches)
    || window.navigator.standalone === true;
  return (
    <BottomSheet title="add to home screen" onClose={onClose}>
      <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.inkMuted, lineHeight: 1.55, marginBottom: 14 }}>
        Shephrd is a web app — add it to your home screen and it opens like a native app, full-screen and fast.
      </div>
      {isStandalone ? (
        <div style={{ background: 'rgba(138,168,150,0.12)', borderRadius: 12, padding: 14, display: 'flex', gap: 10 }}>
          <div style={{ color: C.sage, fontSize: 18 }}>✓</div>
          <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.sage, fontWeight: 600 }}>
            Already installed — you're running the home-screen app.
          </div>
        </div>
      ) : isIOS ? (
        <ol style={{ paddingLeft: 20, margin: 0, fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.navy, lineHeight: 1.6 }}>
          <li>Tap the <b>Share</b> button in Safari's bottom bar</li>
          <li>Scroll down and tap <b>Add to Home Screen</b></li>
          <li>Tap <b>Add</b> — Shephrd appears next to Messages</li>
        </ol>
      ) : isAndroid ? (
        <ol style={{ paddingLeft: 20, margin: 0, fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.navy, lineHeight: 1.6 }}>
          <li>Tap the <b>⋮</b> menu in Chrome</li>
          <li>Tap <b>Install app</b> (or <b>Add to Home screen</b>)</li>
          <li>Confirm — Shephrd installs as an app</li>
        </ol>
      ) : (
        <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13.5, color: C.navy, lineHeight: 1.55 }}>
          On Chrome desktop, click the install icon (⊕) in the address bar.<br/>
          On iPhone/iPad, open this in Safari and use Share → Add to Home Screen.
        </div>
      )}
    </BottomSheet>
  );
}

function PrivacySheet({ email, actions, onClose }) {
  return (
    <BottomSheet title="privacy & data" onClose={onClose}>
      <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14, color: C.navy, lineHeight: 1.6 }}>
        <p style={{ margin: '0 0 12px' }}>
          Shephrd stores <b>your email</b>, the <b>items you post</b>, your <b>comments</b>, and the <b>flocks you're in</b>. Nothing else. No trackers, no ads.
        </p>
        <p style={{ margin: '0 0 12px', color: C.inkMuted }}>
          Links you paste are fetched server-side so xAI can pull metadata. Images you upload are stored on our server and passed to xAI for text extraction. Neither xAI nor we sell or train on your group data.
        </p>
        <p style={{ margin: 0, color: C.inkMuted }}>
          Account: <b style={{ color: C.navy }}>{email}</b>. Deleting your account removes your memberships and posts; flocks you don't own stay alive for the other members.
        </p>
      </div>
      <div style={{ marginTop: 16, background: C.white, borderRadius: 14, overflow: 'hidden' }}>
        <SheetRow icon="⬇" label="Download my data"    hint="we'll email a JSON archive" onClick={() => alert('Coming soon — you\'ll get a download link by email.')} divider/>
        <SheetRow icon="🗑"  label="Delete my account" danger onClick={() => alert('Reply to this email: privacy@shephrd.xyz — we\'ll process within 7 days.')}/>
      </div>
    </BottomSheet>
  );
}

Object.assign(window, {
  YouScreen, JoinHuddleScreen, CreateHuddleScreen,
  BottomSheet, ProfileSheet, EditHuddleSheet, NotificationsSheet, AddToHomeSheet,
  PrivacySheet, TransferOwnershipSheet, DeleteHuddleSheet, SheetRow,
});
