// persona.jsx — Fan / Student / Donor role + team-preference system.
// A lightweight global store (localStorage-backed) that other screens read to
// personalize ordering + emphasis. Exposes:
//   getPersona() / setPersona(id)
//   getTeamPrefs() / toggleTeamPref(id)
//   usePersona()  — React hook returning [persona, setPersona]
//   PersonaPicker — segmented Fan/Student/Donor control + team chips
//   PersonaStrip  — role-aware quick-action strip for Home

const PERSONAS = {
  fan: {
    id: 'fan', label: 'Fan', icon: '★',
    blurb: 'Watch, merch, and game-day moments up top.',
    // ordered priority of home actions
    priority: ['watch', 'merch', 'tickets', 'rewards'],
    greeting: 'Ready for kickoff',
  },
  student: {
    id: 'student', label: 'Student', icon: '✦',
    blurb: 'Student tickets, the section, and social first.',
    priority: ['tickets', 'social', 'rewards', 'merch'],
    greeting: 'The section is calling',
  },
  alumni: {
    id: 'alumni', label: 'Alumni', icon: '🎓',
    blurb: 'Class network, traditions, and homecoming first.',
    priority: ['tickets', 'giving', 'merch', 'rewards'],
    greeting: 'Welcome back, grad',
  },
  donor: {
    id: 'donor', label: 'Donor', icon: '♛',
    blurb: 'NIL, giving impact, and premium access first.',
    priority: ['nil', 'giving', 'premium', 'tickets'],
    greeting: 'Thank you for your support',
  },
};

function getPersona() {
  try { return localStorage.getItem('mtn.persona') || 'fan'; } catch (e) { return 'fan'; }
}
function setPersonaStore(id) {
  try { localStorage.setItem('mtn.persona', id); } catch (e) {}
  window.dispatchEvent(new CustomEvent('mtn-persona', { detail: id }));
}
function getTeamPrefs() {
  try { return JSON.parse(localStorage.getItem('mtn.teamPrefs')) || []; } catch (e) { return []; }
}
function toggleTeamPref(id) {
  const cur = getTeamPrefs();
  const next = cur.includes(id) ? cur.filter(x => x !== id) : [...cur, id];
  try { localStorage.setItem('mtn.teamPrefs', JSON.stringify(next)); } catch (e) {}
  window.dispatchEvent(new CustomEvent('mtn-teamprefs', { detail: next }));
  return next;
}

function usePersona() {
  const [p, setP] = React.useState(getPersona());
  React.useEffect(() => {
    const h = (e) => setP(e.detail);
    window.addEventListener('mtn-persona', h);
    return () => window.removeEventListener('mtn-persona', h);
  }, []);
  return [p, (id) => { setPersonaStore(id); setP(id); }];
}

function useTeamPrefs() {
  const [prefs, setPrefs] = React.useState(getTeamPrefs());
  React.useEffect(() => {
    const h = (e) => setPrefs(e.detail);
    window.addEventListener('mtn-teamprefs', h);
    return () => window.removeEventListener('mtn-teamprefs', h);
  }, []);
  return [prefs, (id) => setPrefs(toggleTeamPref(id))];
}

// ── Persona picker (Me screen) ──
function PersonaPicker() {
  const [persona, setPersona] = usePersona();
  const [prefs, toggle] = useTeamPrefs();
  const cfg = PERSONAS[persona] || PERSONAS.fan;
  const sports = (typeof SPORTS !== 'undefined' ? SPORTS : []).slice(0, 8);
  return (
    <div style={{ padding: '0 16px 18px' }}>
      <div style={{
        borderRadius: DS.r.lg, overflow: 'hidden',
        background: '#15151B', border: `0.5px solid ${WVU.line}`,
      }}>
        <div style={{ padding: '14px 14px 12px' }}>
          <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase', marginBottom: 4 }}>Your experience</div>
          <div style={{ fontFamily: DS.sans, fontSize: 12.5, color: WVU.creamDim, lineHeight: 1.4 }}>How should we tailor your app? You'll see different things first.</div>
        </div>
        {/* Segmented control */}
        <div style={{ display: 'flex', gap: 6, padding: '0 14px 12px' }}>
          {Object.values(PERSONAS).map(p => {
            const on = p.id === persona;
            return (
              <button key={p.id} onClick={() => setPersona(p.id)} style={{
                flex: 1, padding: '12px 6px', borderRadius: DS.r.md, cursor: 'pointer',
                background: on ? `linear-gradient(135deg, ${WVU.gold}, ${WVU.goldDim})` : 'rgba(255,255,255,0.05)',
                border: on ? 'none' : `0.5px solid ${WVU.line}`,
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                transition: 'all 140ms ease',
              }}>
                <span style={{ fontSize: 16, color: on ? WVU.blueDim : WVU.gold }}>{p.icon}</span>
                <span style={{ fontFamily: DS.sans, fontSize: 12.5, fontWeight: 800, color: on ? WVU.blueDim : WVU.cream }}>{p.label}</span>
              </button>
            );
          })}
        </div>
        <div style={{ padding: '0 14px 14px', fontFamily: DS.sans, fontSize: 12.5, color: WVU.creamDim, lineHeight: 1.4 }}>
          <span style={{ color: WVU.gold, fontWeight: 700 }}>{cfg.label}:</span> {cfg.blurb}
        </div>

        {/* Team preferences */}
        <div style={{ borderTop: `0.5px solid ${WVU.line}`, padding: '12px 14px 14px' }}>
          <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase', marginBottom: 4 }}>Favorite teams</div>
          <div style={{ fontFamily: DS.sans, fontSize: 12.5, color: WVU.creamDim, marginBottom: 10 }}>Tap to pick — these surface first across the app.</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {sports.map(s => {
              const on = prefs.includes(s.id);
              return (
                <button key={s.id} onClick={() => toggle(s.id)} style={{
                  padding: '7px 12px', borderRadius: DS.r.pill, cursor: 'pointer',
                  background: on ? hexA(WVU.gold, 0.16) : 'rgba(255,255,255,0.05)',
                  border: `0.5px solid ${on ? hexA(WVU.gold, 0.5) : WVU.line}`,
                  fontFamily: DS.sans, fontSize: 12, fontWeight: 700,
                  color: on ? WVU.gold : WVU.cream,
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  {on && <span style={{ fontSize: 11 }}>✓</span>}
                  {s.name}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Persona-aware quick strip (Home) ──
function PersonaStrip({ persona, onOpenGame, onOpenTickets, onOpenMerch, onOpenNIL, onOpenMe }) {
  const cfg = PERSONAS[persona] || PERSONAS.fan;
  const ACTIONS = {
    watch:   { label: 'Watch', sub: 'Game on now', go: onOpenGame },
    merch:   { label: 'Shop', sub: 'Your size ready', go: onOpenMerch },
    tickets: { label: 'Tickets', sub: 'Sec 108 · Row 14', go: onOpenTickets },
    rewards: { label: 'Rewards', sub: 'Earn today', go: onOpenMe },
    social:  { label: 'Section', sub: 'Student GA', go: onOpenTickets },
    nil:     { label: 'NIL', sub: 'Your athlete', go: onOpenNIL },
    giving:  { label: 'Impact', sub: 'Gold Club', go: onOpenMe },
    premium: { label: 'Club', sub: 'Premium seats', go: onOpenTickets },
  };
  const items = (cfg.priority || []).map(k => ACTIONS[k]).filter(Boolean).slice(0, 4);
  return (
    <div style={{ padding: '0 16px', marginBottom: 18 }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 10,
      }}>
        <div style={{ fontFamily: DS.sans, fontSize: 12, fontWeight: 700, color: WVU.gold, letterSpacing: '0.11em', textTransform: 'uppercase' }}>
          {cfg.icon} For you · {cfg.label}
        </div>
        <div onClick={onOpenMe} style={{ fontFamily: DS.sans, fontSize: 12, color: WVU.creamDim, cursor: 'pointer' }}>Change →</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        {items.map((a, i) => (
          <button key={i} onClick={a.go} data-pulse={i === 0 ? 'true' : undefined} style={{
            padding: '14px 6px', borderRadius: DS.r.md, cursor: 'pointer',
            background: `linear-gradient(160deg, ${WVU.gold}, ${WVU.goldDim})`,
            border: `0.5px solid ${hexA(WVU.gold, 0.6)}`,
            boxShadow: `0 2px 8px rgba(0,0,0,0.25), inset 0 1px 0 ${hexA('#ffffff', 0.18)}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            textAlign: 'center', minHeight: 62, justifyContent: 'center',
          }}>
            <span style={{ fontFamily: DS.sans, fontSize: 12.5, fontWeight: 800, color: WVU.onPrimary || WVU.blueDim, lineHeight: 1.15, whiteSpace: 'nowrap' }}>{a.label}</span>
            <span style={{ fontFamily: DS.mono, fontSize: 9, color: hexA(WVU.onPrimary || WVU.blueDim, 0.78), letterSpacing: '0.02em', lineHeight: 1.15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{a.sub}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { PERSONAS, getPersona, setPersonaStore, getTeamPrefs, toggleTeamPref, usePersona, useTeamPrefs, PersonaPicker, PersonaStrip });
