// VYB LIFE — Circle (Step 5)
// ─────────────────────────────────────────────────────────────────
// Foundation for a private "Circle" of approved friends. This step
// is UI/structure only — no real friend graph, no sharing, no
// network calls. Public sharing remains opt-in and OFF by default.
//
// Future Supabase tables (NOT created in this step):
//   - profiles               (display name, avatar, public_profile_enabled)
//   - friendships            (user_a, user_b, status, since)
//   - friend_requests        (from_user, to_user, status, created_at)
//   - public_profile_settings(user_id, show_active_aura, show_highest, ...)
//   - safe_activity_events   (user_id, type, metadata, created_at, visibility)
//
// Privacy rules (must persist when backend lands):
//   - Friend relationships require mutual consent.
//   - Public profile is opt-in.
//   - Only PUBLIC_PROFILE_SAFE_FIELDS may ever be exposed to friends.
//   - User-generated text (habits, tasks, ideas, notes, mood,
//     reading content, project/context names) is NEVER shared.
// ─────────────────────────────────────────────────────────────────

const FRIENDSHIP_STATUS = {
  NONE: 'none',
  REQUESTED: 'requested',
  PENDING: 'pending',
  FRIENDS: 'friends',
  BLOCKED: 'blocked',
};

const PUBLIC_PROFILE_SAFE_FIELDS = [
  'displayName',
  'avatarUrl',
  'activeAura',
  'highestAura',
  'auraUnlockedCount',
  'weeklyMomentumSummary',
  'safeActivityEvents',
];

// Local-only flag (Circle sharing). Default OFF. Not yet wired to
// any real share path — reserved for future opt-in.
const CIRCLE_SHARING_KEY = 'vyb-circle-sharing-enabled';
const readCircleSharingEnabled = () => {
  try { return localStorage.getItem(CIRCLE_SHARING_KEY) === '1'; }
  catch { return false; }
};
const writeCircleSharingEnabled = (on) => {
  try { localStorage.setItem(CIRCLE_SHARING_KEY, on ? '1' : '0'); } catch {}
};

// Example preview cards. Clearly labeled as examples — never real
// users, never real data. Used only to illustrate what the Circle
// could look like once friends + sharing are enabled.
const CIRCLE_PREVIEW_EXAMPLES = [
  { name: 'Example profile · A', activeAura: 'Reader Flame',  highestAura: 'Prime Aura',  weekly: '4 complete days' },
  { name: 'Example profile · B', activeAura: 'Builder Spark', highestAura: 'Rare Aura',   weekly: '3 complete days' },
  { name: 'Example profile · C', activeAura: 'Quiet Vault',   highestAura: 'Legacy Aura', weekly: '5 complete days' },
];

// ─── Circle Feed filters ────────────────────────────────────────
// Maps top-level filter pill → set of safe activity event types.
// TODO (future): when backend lands, request feed from
//   safe_activity_events table filtered by friendships + filter type.
const CIRCLE_FEED_FILTERS = [
  { id:'all',      label:'All',      types:null },
  { id:'aura',     label:'Aura',     types:['aura_unlocked','active_aura_changed','aura_path_stage_completed'] },
  { id:'momentum', label:'Momentum', types:['today_system_completed','weekly_goal_completed','streak_reached'] },
  { id:'reading',  label:'Reading',  types:['book_finished','reading_milestone'] },
  { id:'ideas',    label:'Ideas',    types:['ideas_milestone'] },
  { id:'tasks',    label:'Tasks',    types:['tasks_milestone'] },
];

// Read safe events: prefer live builder (recomputes from current
// state), fall back to stored events. Caps to 20 newest, dedup by id.
// TODO (future Supabase tables): profiles, friendships,
//   safe_activity_events, public_profile_settings.
const _readCircleFeedEvents = (storeState) => {
  let evts = [];
  try {
    if (typeof window !== 'undefined' && window.buildSafeActivityEvents) {
      evts = window.buildSafeActivityEvents({ storeState }) || [];
    } else {
      const raw = localStorage.getItem('vyb-safe-activity-events');
      evts = raw ? JSON.parse(raw) : [];
    }
  } catch { evts = []; }
  if (!Array.isArray(evts)) evts = [];
  // Safety filter: only safeForPublic OR private_preview visibility.
  evts = evts.filter(e => e && (e.safeForPublic === true || e.visibility === 'private_preview'));
  // Dedup by id, sort desc, cap 20.
  const seen = new Set();
  const out = [];
  for (const e of evts) {
    if (!e.id || seen.has(e.id)) continue;
    seen.add(e.id); out.push(e);
  }
  out.sort((a,b) => (b.timestamp||0) - (a.timestamp||0));
  return out.slice(0, 20);
};

// ─── Reactions (Step 7) ─────────────────────────────────────────
// Controlled reaction set only — no free-text, no emoji picker, no
// custom reactions. One reaction per event per user (toggle off by
// clicking the same one; switch by clicking another).
//
// TODO (future Supabase): table `circle_event_reactions`
//   { id, user_id, event_id, reaction_type, created_at }
//   with unique(user_id, event_id) so one reaction per user per event.
const CIRCLE_REACTIONS = [
  { id:'nice',       label:'Nice',       icon:'thumbs-up' },
  { id:'inspired',   label:'Inspired',   icon:'sparkles' },
  { id:'keep_going', label:'Keep going', icon:'arrow-right' },
];
const _LS_REACTIONS = 'vyb-circle-reactions';
const _readReactions = () => {
  try {
    const raw = localStorage.getItem(_LS_REACTIONS);
    const v = raw ? JSON.parse(raw) : {};
    return (v && typeof v === 'object') ? v : {};
  } catch { return {}; }
};
const _writeReactions = (obj) => {
  try { localStorage.setItem(_LS_REACTIONS, JSON.stringify(obj)); } catch {}
};
const _setReaction = (all, eventId, reactionId) => {
  const next = { ...all };
  if (!reactionId) { delete next[eventId]; }
  else { next[eventId] = { reaction: reactionId, reactedAt: new Date().toISOString() }; }
  _writeReactions(next);
  return next;
};

// ─── CircleModal ────────────────────────────────────────────────
// Modal-based screen (consistent with Profile/Settings). No new
// route, no main-nav slot. Reachable from Profile → "Open Circle".
const CircleModal = ({ onClose, session, store, userName, userAvatar, onGoTo }) => {
  const friends = []; // No real friend graph yet.
  const isEmpty = friends.length === 0;
  const meta = (session && session.user && session.user.user_metadata) || {};
  const name = userName || meta.full_name || meta.name || 'You';
  const avatar = userAvatar || meta.avatar_url || meta.picture || '';
  const initial = (name || '?').charAt(0).toUpperCase();

  const [filter, setFilter] = React.useState('all');
  const [events, setEvents] = React.useState(() =>
    _readCircleFeedEvents(store && store.state));
  const [reactions, setReactions] = React.useState(_readReactions);
  React.useEffect(() => {
    setEvents(_readCircleFeedEvents(store && store.state));
    setReactions(_readReactions());
  }, []);
  const onReact = (eventId, reactionId) => {
    setReactions(prev => {
      const cur = prev[eventId] && prev[eventId].reaction;
      const next = (cur === reactionId) ? null : reactionId; // toggle off / switch
      return _setReaction(prev, eventId, next);
    });
  };

  const activeFilter = CIRCLE_FEED_FILTERS.find(f => f.id === filter) || CIRCLE_FEED_FILTERS[0];
  const visible = activeFilter.types
    ? events.filter(e => activeFilter.types.includes(e.type))
    : events;

  const goMomentum = () => { onClose && onClose(); onGoTo && onGoTo('momentum'); };
  const goHabits   = () => { onClose && onClose(); onGoTo && onGoTo('habits'); };

  return (
    <ModalShell title="Circle" subtitle="See what your people are building." onClose={onClose} maxWidth={620}>
      {/* Empty state */}
      {isEmpty && (
        <div style={{padding:22,border:`1px dashed ${C.borderMid}`,borderRadius:14,
          background:'rgba(255,255,255,0.015)',textAlign:'center',marginBottom:18}}>
          <div style={{width:56,height:56,borderRadius:999,margin:'0 auto 12px',
            background:C.sandFaint,border:`1px solid ${C.sandGlow}`,
            display:'flex',alignItems:'center',justifyContent:'center'}}>
            <Icon name="users" size={22} color={C.sandLight}/>
          </div>
          <div style={{fontSize:14,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>
            Your Circle is empty.
          </div>
          <div style={{fontSize:12,fontWeight:300,color:C.textMuted,marginTop:6,lineHeight:1.55,maxWidth:380,margin:'6px auto 0'}}>
            Add people later to see their Aura, milestones, and safe progress signals.
          </div>
        </div>
      )}

      {/* Coming soon */}
      <div style={{padding:14,borderRadius:12,border:`1px solid ${C.border}`,
        background:'rgba(160,138,86,0.05)',marginBottom:14,
        display:'flex',gap:12,alignItems:'flex-start'}}>
        <Icon name="clock" size={16} color={C.sandLight}/>
        <div style={{minWidth:0,flex:1}}>
          <div style={{fontSize:12,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>Coming soon</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:4,lineHeight:1.55}}>
            Friends and private progress sharing are coming soon. Public sharing will be opt-in.
          </div>
        </div>
      </div>

      {/* Safe sharing explanation */}
      <div style={{padding:14,borderRadius:12,border:`1px solid ${C.border}`,
        background:'rgba(156,203,177,0.04)',marginBottom:18,
        display:'flex',gap:12,alignItems:'flex-start'}}>
        <Icon name="shield-check" size={16} color="#9CCBB1"/>
        <div style={{minWidth:0,flex:1}}>
          <div style={{fontSize:12,fontWeight:700,color:C.textPrimary,letterSpacing:'-0.005em'}}>Share proof, not private details.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:4,lineHeight:1.55}}>
            Your Circle will only see progress signals — Active Aura, Highest Aura, unlocks, streaks, weekly momentum, and safe activity events. Habits, tasks, ideas, notes, mood, and reading content stay private.
          </div>
        </div>
      </div>

      {/* Preview cards (labeled examples) */}
      <SectionHeader label="What your Circle could look like" hint="Examples only — not real users."/>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(220px,1fr))',gap:10,marginBottom:18,opacity:0.82}}>
        {CIRCLE_PREVIEW_EXAMPLES.map((ex, i) => (
          <div key={i} style={{padding:14,borderRadius:12,border:`1px solid ${C.border}`,
            background:'linear-gradient(135deg, rgba(160,138,86,0.05), rgba(255,255,255,0.01))',
            position:'relative'}}>
            <div style={{position:'absolute',top:8,right:8,
              fontSize:8,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
              padding:'2px 6px',borderRadius:999,
              background:'rgba(255,255,255,0.04)',color:C.textFaint,
              border:`1px solid ${C.border}`}}>Example</div>
            <div style={{display:'flex',gap:10,alignItems:'center',marginBottom:10}}>
              <div style={{width:36,height:36,borderRadius:999,background:C.sandFaint,
                border:`1px solid ${C.sandGlow}`,
                display:'flex',alignItems:'center',justifyContent:'center'}}>
                <span style={{fontSize:14,fontWeight:800,color:C.sandLight,fontStyle:'italic'}}>{ex.name.charAt(0)}</span>
              </div>
              <div style={{minWidth:0,flex:1}}>
                <div style={{fontSize:12,fontWeight:700,color:C.textPrimary,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{ex.name}</div>
                <div style={{fontSize:9,fontWeight:600,letterSpacing:'0.16em',textTransform:'uppercase',color:C.textFaint,marginTop:2}}>Preview</div>
              </div>
            </div>
            <div style={{display:'flex',flexDirection:'column',gap:5,fontSize:11,color:C.textSecondary,fontWeight:300}}>
              <div><span style={{color:C.textFaint}}>Active Aura: </span><b style={{color:C.textPrimary,fontWeight:600}}>{ex.activeAura}</b></div>
              <div><span style={{color:C.textFaint}}>Highest Aura: </span><b style={{color:C.textPrimary,fontWeight:600}}>{ex.highestAura}</b></div>
              <div><span style={{color:C.textFaint}}>Weekly Momentum: </span><b style={{color:C.textPrimary,fontWeight:600}}>{ex.weekly}</b></div>
            </div>
          </div>
        ))}
      </div>

      {/* ─── Circle Feed ─────────────────────────────────────── */}
      <SectionHeader label="Circle Feed" hint="Safe progress signals from your Circle."/>

      {/* Your activity preview label */}
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10,flexWrap:'wrap'}}>
        <span style={{fontSize:9,fontWeight:700,letterSpacing:'0.18em',textTransform:'uppercase',
          padding:'3px 8px',borderRadius:999,background:'rgba(160,138,86,0.10)',
          color:C.sandLight,border:`1px solid ${C.sandGlow}`}}>
          Your activity preview
        </span>
        {isEmpty && (
          <span style={{fontSize:10,fontWeight:300,color:C.textFaint,fontStyle:'italic'}}>
            Your Circle is empty for now. This feed will show safe progress signals from approved friends.
          </span>
        )}
      </div>

      {/* Filters */}
      <div style={{display:'flex',gap:6,flexWrap:'wrap',marginBottom:12}}>
        {CIRCLE_FEED_FILTERS.map(f => {
          const on = f.id === filter;
          return (
            <button key={f.id} type="button" onClick={()=>setFilter(f.id)}
              style={{padding:'6px 12px',borderRadius:999,cursor:'pointer',
                background: on ? C.sandFaint : 'transparent',
                border: `1px solid ${on ? C.sand : C.border}`,
                color: on ? C.textPrimary : C.textMuted,
                fontFamily:'Montserrat,sans-serif',
                fontSize:10,fontWeight:600,letterSpacing:'0.12em',textTransform:'uppercase',
                transition:'all 0.18s ease'}}>
              {f.label}
            </button>
          );
        })}
      </div>

      {/* Feed list */}
      {visible.length ? (
        <div style={{display:'flex',flexDirection:'column',gap:0,marginBottom:12,
          border:`1px solid ${C.border}`,borderRadius:12,overflow:'hidden'}}>
          {visible.map((ev, i) => {
            const def = (window.SAFE_ACTIVITY_EVENT_TYPES || {})[ev.type] || {};
            const text = (window.renderSafePublicLabel
              ? window.renderSafePublicLabel(ev, name)
              : `${name} ${ev.title || ''}`.trim());
            const tsLabel = window.formatActivityTime ? window.formatActivityTime(ev.timestamp) : '';
            const md = ev.metadata || {};
            // Secondary line: short safe context (rarity / path / count).
            // NEVER raw user-content (titles, notes, ideas).
            let context = '';
            if (ev.type === 'aura_unlocked' && md.rarity)         context = `${md.rarity} Aura`;
            else if (ev.type === 'active_aura_changed')           context = 'Active Aura';
            else if (ev.type === 'aura_path_stage_completed' && md.pathTitle) context = md.pathTitle;
            else if (ev.type === 'today_system_completed')        context = 'Momentum';
            else if (ev.type === 'weekly_goal_completed')         context = 'Momentum';
            else if (ev.type === 'streak_reached')                context = 'Rhythm';
            else if (ev.type === 'book_finished')                 context = 'Reading';
            else if (ev.type === 'reading_milestone')             context = 'Reading';
            else if (ev.type === 'ideas_milestone')               context = 'Ideas';
            else if (ev.type === 'tasks_milestone')               context = 'Tasks';
            else if (ev.type === 'focus_milestone')               context = 'Focus';
            const myReaction = (reactions[ev.id] && reactions[ev.id].reaction) || null;
            return (
              <div key={ev.id} style={{padding:'12px 14px',
                borderTop: i === 0 ? 'none' : `1px solid ${C.border}`,
                background:'rgba(255,255,255,0.012)'}}>
                <div style={{display:'flex',alignItems:'center',gap:12}}>
                  {/* Avatar */}
                  {avatar ? (
                    <img src={avatar} alt="" style={{width:32,height:32,borderRadius:999,objectFit:'cover',border:`1px solid ${C.sandGlow}`,flexShrink:0}}/>
                  ) : (
                    <div style={{width:32,height:32,borderRadius:999,background:C.sandFaint,
                      border:`1px solid ${C.sandGlow}`,flexShrink:0,
                      display:'flex',alignItems:'center',justifyContent:'center'}}>
                      <span style={{fontSize:13,fontWeight:800,color:C.sandLight,fontStyle:'italic'}}>{initial}</span>
                    </div>
                  )}
                  {/* Icon chip */}
                  <div style={{width:24,height:24,borderRadius:6,flexShrink:0,
                    background:'rgba(160,138,86,0.08)',border:`1px solid ${C.border}`,
                    display:'flex',alignItems:'center',justifyContent:'center'}}>
                    <Icon name={def.icon || 'sparkles'} size={12} color={C.sandLight}/>
                  </div>
                  {/* Body */}
                  <div style={{minWidth:0,flex:1}}>
                    <div style={{fontSize:12,fontWeight:500,color:C.textPrimary,lineHeight:1.4,wordBreak:'break-word'}}>
                      {text}
                    </div>
                    <div style={{fontSize:10,fontWeight:500,letterSpacing:'0.08em',color:C.textFaint,
                      marginTop:3,textTransform:'uppercase'}}>
                      {context ? `${context} · ` : ''}{tsLabel}
                    </div>
                  </div>
                </div>
                {/* Reactions */}
                <div style={{display:'flex',gap:6,flexWrap:'wrap',marginTop:10,paddingLeft:44,minHeight:28}}>
                  {CIRCLE_REACTIONS.map(r => {
                    const on = myReaction === r.id;
                    return (
                      <button key={r.id} type="button"
                        onClick={()=>onReact(ev.id, r.id)}
                        aria-pressed={on}
                        title={on ? `You reacted: ${r.label}` : r.label}
                        style={{display:'inline-flex',alignItems:'center',gap:6,
                          padding:'5px 10px',borderRadius:999,cursor:'pointer',minHeight:28,
                          background: on ? C.sandFaint : 'transparent',
                          border: `1px solid ${on ? C.sand : C.border}`,
                          color: on ? C.textPrimary : C.textMuted,
                          fontFamily:'Montserrat,sans-serif',
                          fontSize:10,fontWeight:600,letterSpacing:'0.10em',textTransform:'uppercase',
                          transition:'all 0.18s ease'}}>
                        <Icon name={r.icon} size={11} color={on ? C.sand : C.textMuted}/>
                        {r.label}
                      </button>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{padding:18,border:`1px dashed ${C.border}`,borderRadius:12,textAlign:'center',marginBottom:12}}>
          <div style={{fontSize:13,fontWeight:700,color:C.textPrimary}}>No signals yet.</div>
          <div style={{fontSize:11,fontWeight:300,color:C.textMuted,marginTop:6,lineHeight:1.5,maxWidth:380,margin:'6px auto 0'}}>
            Complete your system, unlock Aura, or reach a milestone to start building your activity feed.
          </div>
          <div style={{display:'flex',gap:8,justifyContent:'center',marginTop:12,flexWrap:'wrap'}}>
            <Button variant="ghost" size="sm" icon="trending-up" onClick={goMomentum}>Open Momentum</Button>
            <Button variant="ghost" size="sm" icon="check-circle" onClick={goHabits}>Open Habits</Button>
          </div>
        </div>
      )}

      {/* TODO (Step 7+): reactions ("Nice", "Inspired", "Keep going").
          No comments, DMs, or free-text input — ever. */}

      <div style={{fontSize:10,fontWeight:300,color:C.textFaint,lineHeight:1.55,fontStyle:'italic',marginBottom:18}}>
        No comments yet. Only simple reactions to safe progress signals. Private details stay hidden.
      </div>

      <div style={{fontSize:10,fontWeight:300,color:C.textFaint,lineHeight:1.55,fontStyle:'italic'}}>
        Your Circle will only see progress signals. Private details stay hidden.
      </div>
    </ModalShell>
  );
};

// Public helper: count of safe events ready to show in the Circle
// Feed. Used by the Profile Circle card preview.
const getCircleFeedEventCount = (storeState) => _readCircleFeedEvents(storeState).length;

Object.assign(window, {
  FRIENDSHIP_STATUS,
  PUBLIC_PROFILE_SAFE_FIELDS,
  CIRCLE_SHARING_KEY,
  CIRCLE_FEED_FILTERS,
  CIRCLE_REACTIONS,
  readCircleSharingEnabled,
  writeCircleSharingEnabled,
  getCircleFeedEventCount,
  CircleModal,
});
