const DSj = window.RallyAIBusiness_2d8789;
const { PixelIcon: JIcon, StatBig: JStat, MeterBar: JMeter, Chip: JChip, Badge: JBadge } = DSj;

function JourneyScreen({ D, openStage, segId }) {
  const [open, setOpen] = React.useState(typeof openStage === 'number' ? openStage : -1);
  const [quoteTp, setQuoteTp] = React.useState(null);
  const [qSort, setQSort] = React.useState('top');
  const [segSel, setSegSel] = React.useState(segId || null);
  React.useEffect(() => { if (typeof openStage === 'number') setOpen(openStage); }, [openStage, D.id]);
  React.useEffect(() => { setSegSel(segId || null); }, [segId, D.id]);
  const seg = segSel ? D.segments.find(s => s.id === segSel) : null;
  const SEG_METRIC = { 2: 'ces', 3: 'csat', 4: 'vfm', 5: 'nps' };
  const journey = D.journey.map((st, i) => {
    if (!seg || !(i in SEG_METRIC)) return seg ? { ...st, est: true } : st;
    return { ...st, metric: String(seg[SEG_METRIC[i]]), est: true };
  });
  const health = seg ? ((seg.csat + seg.nps + seg.ces + seg.vfm) / 4).toFixed(1) : D.health;
  const pill = (on) => ({ display: 'inline-flex', alignItems: 'center', gap: 6, border: '1px solid var(--ink)', padding: '5px 10px', cursor: 'pointer', fontSize: 12, fontWeight: 500, background: on ? 'var(--ink)' : 'transparent', color: on ? 'var(--white)' : 'var(--ink)', whiteSpace: 'nowrap', flexShrink: 0 });
  return <div style={{ '--accent': 'var(--yellow)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 16px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Journey Map</h1>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>{seg ? `${D.name} · ${seg.count} profiles · health ${health}/5` : `${D.name} · 6 stages · health ${health}/5`}</div>
      <div className="no-bar" style={{ display: 'flex', gap: 6, marginTop: 12, overflowX: 'auto' }}>
        <span onClick={() => setSegSel(null)} style={pill(!segSel)}>{D.id === 'brand' ? 'Brand' : 'Outlet'}</span>
        {D.segments.map(s => <span key={s.id} onClick={() => setSegSel(s.id)} style={pill(segSel === s.id)}>{s.label}</span>)}
      </div>
    </div>
    <div style={{ flex: 1 }}>
      {journey.map((st, i) => {
        const on = open === i;
        return <div key={i} style={{ borderTop: '1px solid var(--ink)', background: on ? 'var(--sage)' : 'transparent', transition: 'background 120ms var(--ease-snap)' }}>
          <div onClick={() => setOpen(on ? -1 : i)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 24px', cursor: 'pointer' }}>
            <span className="u-pixel">{String(i + 1).padStart(2, '0')}</span>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {st.fix ? <JBadge value="!" offset={{ top: 'calc(50% - 7.5px)', right: -22 }}><span style={{ fontSize: 18, fontWeight: 700 }}>{st.stage}</span></JBadge> : <span style={{ fontSize: 18, fontWeight: 700 }}>{st.stage}</span>}
              </div>
              <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{st.title}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 22, fontWeight: 700, display: 'flex', alignItems: 'baseline', gap: 6, justifyContent: 'flex-end' }}>{st.metric}{st.est && <span className="u-pixel" style={{ fontSize: 9, color: 'var(--text-muted)' }}>EST</span>}</div>
              <div className="u-label" style={{ color: 'var(--text-muted)' }}>{st.label}</div>
            </div>
          </div>
          {on && <div style={{ padding: '4px 24px 18px', display: 'grid', gap: 10 }}>
            {st.fix && <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', background: 'var(--accent)', padding: '10px 12px' }}>
              <JIcon name="alert" size={18} style={{ flexShrink: 0, marginTop: 1 }} />
              <span style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35 }}>{st.fix}</span>
            </div>}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <JIcon name="value-drivers" size={16} />
              <span className="u-label" style={{ color: 'var(--text-muted)' }}>Value drivers</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '92px 1fr', gap: '6px 10px' }}>
                {(RallyData.STAGE_DRIVERS[st.stage] || []).map(([n, d], k) => <React.Fragment key={k}>
                  <span style={{ fontSize: 13, fontWeight: 700 }}>{n}</span>
                  <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.35 }}>{d}</span>
                </React.Fragment>)}
            </div>
            <div style={{ borderTop: '1px solid rgba(32,36,27,.3)', paddingTop: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
              <JIcon name="touchpoint" size={16} />
              <span className="u-label" style={{ color: 'var(--text-muted)' }}>Touchpoints</span>
            </div>
            {st.tps.map(([name, pct], j) => <div key={j} style={{ display: 'flex', alignItems: 'flex-end', gap: 12 }}>
                <JMeter label={name} value={pct} max={100} display={pct + '%'} accent={j === 0} style={{ flex: 1 }} />
                <span onClick={(e) => { e.stopPropagation(); setQuoteTp(name); }} style={{ cursor: 'pointer', display: 'inline-flex' }}><JIcon name="quote" size={20} /></span>
              </div>)}
            {st.comp && <div style={{ marginTop: 4 }}>
              <span className="u-label" style={{ color: 'var(--text-muted)' }}>Also considered</span>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
                {st.comp.map(([n, p], k) => <JChip key={k} variant="outline">{n} · {p}%</JChip>)}
              </div>
            </div>}
            {st.est && <div className="u-label" style={{ color: 'var(--text-muted)' }}>{seg ? 'Estimated from ' + seg.label + ' quest responses' : `Estimated from quest samples · run a ${st.stage.toLowerCase()} quest to verify`}</div>}
          </div>}
        </div>;
      })}
    </div>
    <div style={{ background: 'var(--accent)', padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <JStat value={health} ghost="/5" label={seg ? seg.label + ' health' : 'Journey health'} size="title" />
      <JIcon name="journey" size={36} />
    </div>
    {quoteTp && <div onClick={() => setQuoteTp(null)} style={{ position: 'absolute', inset: 0, background: 'rgba(32,36,27,.35)', zIndex: 30 }}></div>}
    {quoteTp && (() => {
      const all = RallyData.TP_QUOTES[quoteTp] || [];
      const list = qSort === 'recent' ? [...all].sort((a, b) => (a[2] || 99) - (b[2] || 99)) : all;
      const ago = (d) => d === undefined ? '' : d <= 1 ? 'Today' : d < 7 ? d + 'd ago' : Math.round(d / 7) + 'w ago';
      return <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, background: 'var(--paper)', borderTop: '1px solid var(--ink)', zIndex: 31, maxHeight: '62%', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 24px', borderBottom: '1px solid var(--ink)', flexShrink: 0 }}>
          <span className="u-pixel">QUOTES · {quoteTp.toUpperCase()}</span>
          <span onClick={() => setQuoteTp(null)} style={{ cursor: 'pointer', display: 'inline-flex' }}><JIcon name="close" size={16} /></span>
        </div>
        <div style={{ display: 'flex', gap: 6, padding: '12px 24px 0', flexShrink: 0 }}>
          {[['top', 'Top'], ['recent', 'Recent']].map(([id, l]) => <span key={id} onClick={() => setQSort(id)} style={{ border: '1px solid var(--ink)', padding: '4px 10px', cursor: 'pointer', fontSize: 12, fontWeight: 500, background: qSort === id ? 'var(--ink)' : 'transparent', color: qSort === id ? 'var(--white)' : 'var(--ink)' }}>{l}</span>)}
          <span className="u-label" style={{ color: 'var(--text-muted)', marginLeft: 'auto', alignSelf: 'center' }}>{list.length} quotes</span>
        </div>
        <div style={{ padding: '0 24px 20px', overflowY: 'auto' }}>
          {list.length === 0 && <div className="u-label" style={{ color: 'var(--text-muted)', padding: '16px 0' }}>No quotes yet — run a quest on this touchpoint</div>}
          {list.map(([q, who, d], i) => <div key={i} style={{ padding: '14px 0', borderBottom: i < list.length - 1 ? '1px solid rgba(32,36,27,.2)' : 'none' }}>
            <div style={{ fontSize: 15, fontWeight: 500, fontStyle: 'italic', lineHeight: 1.4, textWrap: 'pretty' }}>"{q}"</div>
            <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>{who} · quest response{d !== undefined ? ' · ' + ago(d) : ''}</div>
          </div>)}
        </div>
      </div>;
    })()}
  </div>;
}

Object.assign(window, { JourneyScreen });
