// subscribe.jsx — Signal Subscription experience
// Triggered when a new person scans your QR / taps your NFC / opens your Beeprd.

const SUBSCRIBE_CATEGORIES = [
  {
    key: 'platforms',
    title: 'Platforms',
    sub: 'Auto-pulled from connected accounts',
    items: [
      { id:'youtube',    p:'youtube',   label:'YouTube Uploads',   est:'2 / week',  defaultTier:1 },
      { id:'instagram',  p:'instagram', label:'Instagram Posts',   est:'5 / week',  defaultTier:0 },
      { id:'linkedin',   p:'linkedin',  label:'LinkedIn Updates',  est:'3 / week',  defaultTier:2 },
      { id:'x',          p:'x',         label:'X (Twitter) Posts', est:'12 / week', defaultTier:1 },
      { id:'podcast',    p:'podcast',   label:'Podcast Episodes',  est:'1 / week',  defaultTier:2 },
      { id:'newsletter', p:'blog',      label:'Newsletter Releases', est:'1 / week', defaultTier:2 },
    ],
  },
  {
    key: 'moments',
    title: 'Moments',
    sub: 'High-signal milestones — rare but important',
    items: [
      { id:'launches',   icon:'broadcast', label:'Product Launches',         est:'rare',    defaultTier:2 },
      { id:'events',     icon:'events',    label:'Events & Appearances',     est:'monthly', defaultTier:2 },
      { id:'business',   icon:'analytics', label:'Business Updates',         est:'monthly', defaultTier:1 },
      { id:'hiring',     icon:'profile',   label:'Hiring Announcements',     est:'rare',    defaultTier:1 },
      { id:'investment', icon:'wallet',    label:'Investment Opportunities', est:'rare',    defaultTier:2 },
      { id:'speaking',   icon:'broadcast', label:'Speaking Events',          est:'monthly', defaultTier:2 },
    ],
  },
];

const TIER_META = [
  { id:0, label:'Off',     icon:null,        cls:'tier-off',     desc:"You won't be pinged" },
  { id:1, label:'Digest',  icon:'analytics', cls:'tier-digest',  desc:'Weekly digest only' },
  { id:2, label:'Instant', icon:'bell',      cls:'tier-instant', desc:'Beep me as it happens' },
];

// ─────────────────────────────────────────────────────────────────────────
// Main flow
// ─────────────────────────────────────────────────────────────────────────
const SubscribeModal = ({ onClose, subject = defaultSubject }) => {
  const [scene, setScene] = React.useState('reveal'); // reveal → select → confirm
  const [picks, setPicks] = React.useState(() => {
    const init = {};
    SUBSCRIBE_CATEGORIES.forEach(c => c.items.forEach(i => { init[i.id] = i.defaultTier; }));
    return init;
  });

  React.useEffect(() => {
    if (scene === 'reveal') {
      const t = setTimeout(() => setScene('select'), 1900);
      return () => clearTimeout(t);
    }
  }, [scene]);

  const subscribedItems = Object.entries(picks).filter(([,v]) => v > 0);
  const instantCount    = Object.values(picks).filter(v => v === 2).length;
  const digestCount     = Object.values(picks).filter(v => v === 1).length;

  const setAll = (tier) => {
    const next = {};
    SUBSCRIBE_CATEGORIES.forEach(c => c.items.forEach(i => { next[i.id] = tier; }));
    setPicks(next);
  };

  return (
    <div className="sub-scrim" onClick={onClose}>
      <style>{SUB_CSS}</style>
      <div className="sub-frame" onClick={(e) => e.stopPropagation()}>
        {/* Phone status bar */}
        <div className="sub-status">
          <span className="mono">9:41</span>
          <div className="row gap-sm" style={{color:'var(--ink)'}}>
            <span style={{letterSpacing:'.05em'}}>●●●</span>
            <span style={{fontSize:11}}>5G</span>
            <span style={{fontSize:11}}>100%</span>
          </div>
        </div>

        {scene === 'reveal'  && <SubReveal subject={subject}/>}
        {scene === 'select'  && (
          <SubSelect
            subject={subject}
            picks={picks} setPicks={setPicks}
            setAll={setAll}
            onClose={onClose}
            onConfirm={() => setScene('confirm')}
            counts={{ instant: instantCount, digest: digestCount, total: subscribedItems.length }}
          />
        )}
        {scene === 'confirm' && (
          <SubConfirm
            subject={subject}
            picks={picks}
            onDone={onClose}
          />
        )}
      </div>
    </div>
  );
};

const defaultSubject = {
  name: 'Clarence Holmes',
  init: 'CH',
  role: 'Entrepreneur · Investor · Creator',
  loc:  'Atlanta, GA',
  ctx:  'You scanned at Atlanta Tech Week',
  id:   'CLARENCE',
};

// ─────────────────────────────────────────────────────────────────────────
// Scene 1: REVEAL (the pager beep moment)
// ─────────────────────────────────────────────────────────────────────────
const SubReveal = ({ subject }) => (
  <div className="sub-body sub-reveal">
    <div className="sub-reveal-pulse"/>
    <div className="sub-reveal-pulse two"/>
    <div className="sub-reveal-pulse three"/>

    <div className="sub-reveal-pager">
      <PagerCard msg="BEEP" id={subject.id} subtitle="Beeprd Scan" actions={false} compact/>
    </div>
    <div className="sub-reveal-text">
      <div className="eyebrow" style={{marginBottom:8, color:'var(--accent)'}}>Beeprd · New Connection</div>
      <div className="serif" style={{fontSize:30, lineHeight:1.1}}>Pinging {subject.name.split(' ')[0]}…</div>
      <div className="tiny mono" style={{color:'var(--mute)', marginTop:8, letterSpacing:'.1em', textTransform:'uppercase'}}>{subject.ctx}</div>
    </div>
  </div>
);

// ─────────────────────────────────────────────────────────────────────────
// Scene 2: SELECT
// ─────────────────────────────────────────────────────────────────────────
const SubSelect = ({ subject, picks, setPicks, setAll, onClose, onConfirm, counts }) => {
  const cycle = (id) => setPicks(p => ({ ...p, [id]: (p[id] + 1) % 3 }));
  const set   = (id, tier) => setPicks(p => ({ ...p, [id]: tier }));

  return (
    <div className="sub-body">
      <div className="sub-header">
        <button className="sub-x" onClick={onClose} aria-label="Close">
          <I name="plus" size={14} style={{transform:'rotate(45deg)'}}/>
        </button>
        <div className="sub-eyebrow"><I name="badgeCheck" size={11}/> Beeprd</div>
        <div style={{width:30}}/>
      </div>

      <div className="sub-subject">
        <div className="avatar lg" style={{margin:'0 auto 12px'}}>{subject.init}</div>
        <div className="row" style={{justifyContent:'center', gap:6, marginBottom:2}}>
          <div className="h2" style={{fontSize:20}}>{subject.name}</div>
          <span style={{color:'var(--accent)'}}><I name="badgeCheck" size={14}/></span>
        </div>
        <div className="tiny" style={{color:'var(--mute)'}}>{subject.role}</div>
      </div>

      <div className="sub-headline">
        <h2 className="serif sub-headline-text">Choose the signals that matter.</h2>
        <div className="subtle" style={{fontSize:13}}>You can mute or rebalance any of these later.</div>
      </div>

      <div className="sub-quick">
        <button className="sub-quick-btn" onClick={() => setAll(2)}>
          <I name="bell" size={13}/> Instant for all
        </button>
        <button className="sub-quick-btn" onClick={() => setAll(1)}>
          <I name="analytics" size={13}/> Weekly digest
        </button>
        <button className="sub-quick-btn ghost" onClick={() => setAll(0)}>
          Reset
        </button>
      </div>

      <div className="sub-list">
        {SUBSCRIBE_CATEGORIES.map((cat) => (
          <div key={cat.key} className="sub-section">
            <div className="sub-section-head">
              <div className="eyebrow">{cat.title}</div>
              <div className="tiny" style={{color:'var(--mute-2)'}}>{cat.sub}</div>
            </div>
            <div className="sub-section-body">
              {cat.items.map((it, idx) => {
                const tier = picks[it.id];
                return (
                  <div key={it.id} className={"sub-row " + (tier > 0 ? 'on' : 'off')} onClick={() => cycle(it.id)}>
                    <div className="sub-row-icon">
                      {it.p
                        ? <PlatformIcon kind={it.p} size={32}/>
                        : <div className="sub-row-glyph"><I name={it.icon} size={16}/></div>
                      }
                    </div>
                    <div className="sub-row-text">
                      <div className="sub-row-label">{it.label}</div>
                      <div className="sub-row-meta">
                        <span className="mono">~{it.est}</span>
                        <span className="sub-row-dot">·</span>
                        <span>{TIER_META[tier].desc}</span>
                      </div>
                    </div>
                    <TierPicker tier={tier} onSet={(t) => set(it.id, t)}/>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      <div className="sub-cta">
        <div className="sub-cta-summary">
          <div className="sub-cta-count num">
            {counts.total}<span className="sub-cta-count-tail">/ {SUBSCRIBE_CATEGORIES.reduce((s,c) => s + c.items.length, 0)} signals</span>
          </div>
          <div className="tiny" style={{color:'var(--mute)'}}>
            <span style={{color:'var(--accent)'}}>●</span> {counts.instant} instant
            &nbsp;&nbsp;
            <span style={{color:'var(--good)'}}>●</span> {counts.digest} digest
          </div>
        </div>
        <button
          className="btn btn-primary sub-cta-btn"
          onClick={onConfirm}
          disabled={counts.total === 0}
          style={{opacity: counts.total === 0 ? .4 : 1}}
        >
          Subscribe <I name="arrow" size={14}/>
        </button>
      </div>
    </div>
  );
};

const TierPicker = ({ tier, onSet }) => (
  <div className="tier-picker" onClick={(e) => e.stopPropagation()}>
    {TIER_META.map((t) => (
      <button
        key={t.id}
        className={"tier-pill " + t.cls + (tier === t.id ? ' on' : '')}
        onClick={() => onSet(t.id)}
        title={t.desc}
        aria-label={t.label}
      >
        {t.icon ? <I name={t.icon} size={11.5} stroke={2}/> : <span className="tier-off-glyph">/</span>}
      </button>
    ))}
  </div>
);

// ─────────────────────────────────────────────────────────────────────────
// Scene 3: CONFIRMATION (the beep)
// ─────────────────────────────────────────────────────────────────────────
const SubConfirm = ({ subject, picks, onDone }) => {
  const subbed = [];
  SUBSCRIBE_CATEGORIES.forEach(c => c.items.forEach(i => {
    if (picks[i.id] > 0) subbed.push({ ...i, tier: picks[i.id] });
  }));
  const instantOnes = subbed.filter(s => s.tier === 2);

  return (
    <div className="sub-body sub-confirm">
      <div style={{textAlign:'center'}}>
        <div className="sub-check">
          <div className="sub-check-ring"/>
          <I name="check" size={36} stroke={2.4}/>
        </div>

        <div className="eyebrow" style={{marginTop:14, color:'var(--accent)'}}>Beeprd · Connected</div>
        <div className="serif" style={{fontSize:30, lineHeight:1.1, marginTop:6}}>You're in.</div>
        <div className="subtle" style={{marginTop:6, fontSize:13, maxWidth:280, margin:'6px auto 0'}}>
          You'll be pinged when {subject.name.split(' ')[0]} shares anything that matters.
        </div>
      </div>

      <div className="sub-confirm-pager">
        <PagerCard msg="SUBSCRIBED" id={subject.id} subtitle={`From ${subject.name}`} actions={false} compact/>
      </div>

      <div className="sub-confirm-list">
        <div className="eyebrow" style={{padding:'0 4px 8px'}}>You'll now receive</div>
        <div className="sub-confirm-rows">
          {subbed.slice(0, 6).map((s) => (
            <div key={s.id} className="sub-confirm-row">
              <span className="check on" style={{width:14, height:14, borderWidth:0}}><I name="check" size={9} stroke={2.4}/></span>
              <span style={{flex:1, fontSize:13, fontWeight:500}}>{s.label}</span>
              <span className={"tier-pill on " + TIER_META[s.tier].cls} style={{cursor:'default', width:22, height:22}}>
                {TIER_META[s.tier].icon ? <I name={TIER_META[s.tier].icon} size={11}/> : '/'}
              </span>
            </div>
          ))}
          {subbed.length > 6 && (
            <div className="tiny" style={{padding:'8px 4px 0', color:'var(--mute)'}}>+ {subbed.length - 6} more</div>
          )}
        </div>
      </div>

      <div className="sub-confirm-preview">
        <div className="sub-confirm-preview-bell"><I name="bell" size={13}/></div>
        <div style={{flex:1, minWidth:0}}>
          <div className="tiny mono" style={{color:'var(--mute)', letterSpacing:'.08em'}}>NEXT TIME</div>
          <div style={{fontSize:13, marginTop:1}}>
            <b>BEEP</b> — {subject.name.split(' ')[0]} {instantOnes[0] ? `posted a new ${instantOnes[0].label.toLowerCase().replace(/s$/, '')}` : 'shared an update'}.
          </div>
        </div>
      </div>

      <div className="sub-cta">
        <button className="btn btn-ghost" onClick={onDone} style={{flex:1}}>Adjust</button>
        <button className="btn btn-primary sub-cta-btn" onClick={onDone}>Done</button>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────
// Styles (scoped — kept here to keep app CSS uncluttered)
// ─────────────────────────────────────────────────────────────────────────
const SUB_CSS = `
.sub-scrim{
  position:fixed; inset:0; z-index:150;
  background:color-mix(in srgb, var(--ink) 60%, transparent);
  backdrop-filter:blur(10px) saturate(140%);
  -webkit-backdrop-filter:blur(10px) saturate(140%);
  display:grid; place-items:center;
  animation:sub-fade .18s ease;
}
@keyframes sub-fade{from{opacity:0}to{opacity:1}}
.sub-frame{
  width:400px; max-width:calc(100vw - 32px);
  height:min(800px, calc(100vh - 32px));
  background:var(--bg);
  border-radius:38px;
  border:1px solid var(--line);
  box-shadow:0 40px 100px -30px rgba(0,0,0,0.45);
  overflow:hidden;
  display:flex; flex-direction:column;
  animation:sub-rise .32s cubic-bezier(.2,.7,.2,1);
  position:relative;
}
@keyframes sub-rise{from{transform:translateY(20px) scale(.98); opacity:0}to{transform:none; opacity:1}}
.sub-status{
  display:flex; align-items:center; justify-content:space-between;
  padding:14px 22px 0; font-size:12.5px; font-weight:600;
  flex-shrink:0;
}
.sub-body{
  flex:1; min-height:0; display:flex; flex-direction:column;
  animation:sub-fade .26s ease;
}
.sub-header{
  display:flex; align-items:center; justify-content:space-between;
  padding:10px 18px 0; flex-shrink:0;
}
.sub-x{
  width:30px; height:30px; border-radius:8px;
  display:grid; place-items:center;
  background:var(--surface-2); border:1px solid var(--line);
  color:var(--mute);
}
.sub-eyebrow{
  display:inline-flex; align-items:center; gap:6px;
  font-size:11px; font-weight:600; letter-spacing:.06em;
  color:var(--accent); text-transform:uppercase;
}

.sub-subject{ text-align:center; padding:14px 22px 6px; flex-shrink:0; }

.sub-headline{ padding:14px 22px 12px; text-align:center; flex-shrink:0; }
.sub-headline-text{
  font-family:"Instrument Serif"; font-weight:400; font-size:28px;
  line-height:1.1; letter-spacing:-0.01em; margin:0 0 6px;
}

.sub-quick{
  display:flex; gap:6px; padding:0 18px 14px; flex-shrink:0;
}
.sub-quick-btn{
  flex:1; padding:7px 8px; border-radius:9px;
  background:var(--surface); border:1px solid var(--line);
  font-size:11.5px; font-weight:500; color:var(--ink-2);
  display:inline-flex; align-items:center; justify-content:center; gap:5px;
}
.sub-quick-btn:active{transform:translateY(0.5px)}
.sub-quick-btn:hover{background:var(--surface-2)}
.sub-quick-btn.ghost{ flex:0 0 auto; color:var(--mute); padding:7px 12px; }

.sub-list{
  flex:1; min-height:0; overflow-y:auto; padding:0 18px 24px;
  scroll-behavior:smooth;
}
.sub-section{ margin-bottom:14px; }
.sub-section-head{
  display:flex; align-items:baseline; justify-content:space-between;
  padding:6px 4px 8px;
}
.sub-section-head .tiny{ max-width:170px; text-align:right; }
.sub-section-body{
  background:var(--surface); border:1px solid var(--line); border-radius:14px;
  overflow:hidden;
}

.sub-row{
  display:flex; align-items:center; gap:12px;
  padding:11px 12px;
  border-top:1px solid var(--line-2);
  cursor:pointer; transition:background .12s ease;
  user-select:none;
}
.sub-row:first-child{ border-top:0; }
.sub-row:hover{ background:var(--surface-2); }
.sub-row.off .sub-row-label{ color:var(--mute); }
.sub-row.off .sub-row-icon{ opacity:.55; filter:saturate(.4); }
.sub-row-glyph{
  width:32px; height:32px; border-radius:9px;
  background:var(--accent-soft); color:var(--accent-ink);
  display:grid; place-items:center;
}
.sub-row-text{ flex:1; min-width:0; }
.sub-row-label{ font-size:13.5px; font-weight:600; line-height:1.25; }
.sub-row-meta{ font-size:11px; color:var(--mute); margin-top:2px; display:flex; gap:5px; align-items:center; }
.sub-row-dot{ color:var(--mute-2); }

.tier-picker{
  display:inline-flex; gap:2px; padding:3px;
  background:var(--surface-2); border:1px solid var(--line);
  border-radius:999px; flex-shrink:0;
}
.tier-pill{
  width:26px; height:26px; border-radius:999px;
  display:grid; place-items:center;
  color:var(--mute-2);
  transition: background .14s ease, color .14s ease, transform .12s ease;
}
.tier-pill:hover{ color:var(--ink-2); }
.tier-pill.on{ color:#fff; transform:scale(1.02); }
.tier-pill.tier-off.on    { background:var(--mute);   color:#fff; }
.tier-pill.tier-digest.on { background:var(--good);   color:#fff; }
.tier-pill.tier-instant.on{ background:var(--accent); color:#fff; box-shadow:0 0 0 3px color-mix(in srgb, var(--accent) 20%, transparent); }
.tier-off-glyph{ font-family:"JetBrains Mono"; font-size:13px; line-height:1; transform:rotate(20deg); }

.sub-cta{
  display:flex; align-items:center; gap:12px;
  padding:14px 18px 18px;
  border-top:1px solid var(--line-2);
  background:color-mix(in srgb, var(--bg) 92%, transparent);
  backdrop-filter:blur(8px);
  flex-shrink:0;
}
.sub-cta-summary{ flex:1; min-width:0; }
.sub-cta-count{ font-size:18px; font-weight:600; }
.sub-cta-count-tail{ font-size:12px; font-weight:500; color:var(--mute); margin-left:4px; }
.sub-cta-btn{ padding:11px 18px; font-size:14px; }

/* REVEAL */
.sub-reveal{
  position:relative; flex:1; display:flex; flex-direction:column;
  align-items:center; justify-content:center; padding:22px;
  overflow:hidden;
}
.sub-reveal-pulse{
  position:absolute; width:240px; height:240px; border-radius:50%;
  border:1.5px solid var(--accent); opacity:0;
  animation:pulse 2s ease-out infinite;
}
.sub-reveal-pulse.two{ animation-delay:.5s; }
.sub-reveal-pulse.three{ animation-delay:1s; }
@keyframes pulse{
  0%  { transform:scale(.4); opacity:.6; }
  80% { opacity:0; }
  100%{ transform:scale(1.6); opacity:0; }
}
.sub-reveal-pager{
  position:relative; z-index:1; width:240px;
  animation:reveal-pager .8s cubic-bezier(.2,.7,.2,1);
}
@keyframes reveal-pager{
  from{ transform:translateY(20px) scale(.9); opacity:0;}
  to  { transform:none; opacity:1;}
}
.sub-reveal-text{
  position:relative; z-index:1; text-align:center; margin-top:26px;
  animation:reveal-text .6s .25s both ease;
}
@keyframes reveal-text{ from{opacity:0; transform:translateY(8px)} to{opacity:1; transform:none}}

/* CONFIRM */
.sub-confirm{ padding:24px 22px; gap:18px; overflow-y:auto; }
.sub-check{
  position:relative; width:80px; height:80px; margin:8px auto 0;
  border-radius:50%; background:var(--accent);
  display:grid; place-items:center; color:#fff;
  animation:check-pop .4s cubic-bezier(.2,.7,.2,1);
}
.sub-check-ring{
  position:absolute; inset:-6px; border-radius:50%;
  border:1.5px solid var(--accent); opacity:.3;
  animation:ring 1.4s ease-out infinite;
}
@keyframes check-pop{ from{transform:scale(.5); opacity:0} to{transform:none; opacity:1}}
@keyframes ring{ 0%{transform:scale(1); opacity:.35} 100%{transform:scale(1.4); opacity:0}}

.sub-confirm-pager{
  width:240px; margin:18px auto 0;
}
.sub-confirm-list{ margin-top:8px; }
.sub-confirm-rows{
  background:var(--surface); border:1px solid var(--line); border-radius:12px;
  padding:8px 12px;
}
.sub-confirm-row{
  display:flex; align-items:center; gap:10px;
  padding:8px 4px; border-top:1px solid var(--line-2);
}
.sub-confirm-row:first-child{ border-top:0; }

.sub-confirm-preview{
  display:flex; align-items:center; gap:12px;
  padding:12px 14px; margin-top:8px;
  border-radius:12px;
  background:var(--accent-soft);
  color:var(--accent-ink);
}
.sub-confirm-preview-bell{
  width:32px; height:32px; border-radius:50%;
  background:var(--accent); color:#fff;
  display:grid; place-items:center;
  flex-shrink:0;
}

/* Make sub-list scrollbar subtle on mobile */
.sub-list::-webkit-scrollbar{ width:4px; }
.sub-list::-webkit-scrollbar-thumb{ background:color-mix(in srgb, var(--ink) 10%, transparent); border-radius:99px; }
`;

Object.assign(window, { SubscribeModal });
