const DSh = window.RallyAIBusiness_2d8789;
const { RallyFace: HFace, PixelIcon: HIcon, ListRow: HRow, StatBig: HStat, Button: HButton, Badge: HBadge, SpeechBox: HSpeech } = DSh;


function HomeScreen({ D, scopeId, nav, quests, custs, userMode, setScope }) {
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => setIdx(0), [scopeId, userMode]);
  const owner = userMode === 'owner';
  const insSrc = owner ? RallyData.brand : D;
  const ins = insSrc.insights[idx % insSrc.insights.length];
  const live = quests.filter(q => q.status === 'Live');
  const open = custs.filter(c => c.on).length;
  const k = D.kpis;
  const happy = ((k.csat + k.nps + k.ces + k.vfm) / 4).toFixed(1);
  const delta = { brand: '+0.2', flagship: '+0.1', kiosk: '+0.3' }[D.id];
  const go = () => ins.v === 'segment' ? nav('segment', ins.a) : ins.v === 'compare' ? nav('compare') : nav(ins.v, ins.a);
  return <div style={{ '--accent': 'var(--orange)', display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
    <div style={{ padding: '18px 24px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'flex-start', padding: '2px 0 12px' }}><HFace size={46} talking /></div>
      <HSpeech pointer="top" pointerOffset={26} style={{ padding: '16px 18px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <span className="u-pixel">RALLY · DAILY INSIGHTS</span>
          <span className="u-label" style={{ color: 'var(--text-muted)' }}>{idx % insSrc.insights.length + 1}/{insSrc.insights.length}</span>
        </div>
        <div style={{ fontSize: 18, fontWeight: 500, lineHeight: 1.35, textWrap: 'pretty' }}>{ins.t}</div>
        <div style={{ display: 'flex', gap: 10, marginTop: 14, justifyContent: 'space-between' }}>
          <HButton variant="accent" size="sm" onClick={go}>{ins.label}</HButton>
          <HButton variant="ghost" size="sm" onClick={() => setIdx(i => i + 1)} aria-label="Next insight"><HIcon name="arrow-right" size={14} /></HButton>
        </div>
      </HSpeech>
    </div>
    {owner && <div style={{ background: 'var(--orange)', padding: '22px 24px 24px' }}>
      <span className="u-pixel">HEALTH PULSE · ALL OUTLETS</span>
      <div style={{ display: 'grid', gap: 10, marginTop: 12 }}>
        {Object.values(RallyData.outlets).map(o => {
          const ok = o.kpis, h = ((ok.csat + ok.nps + ok.ces + ok.vfm) / 4).toFixed(1);
          const od = { flagship: '+0.1', kiosk: '+0.3' }[o.id];
          const worstV = Math.min(ok.csat, ok.nps, ok.ces, ok.vfm);
          const worstL = [['CSAT', ok.csat], ['NPS', ok.nps], ['Effort', ok.ces], ['Value for money', ok.vfm]].find(x => x[1] === worstV)[0];
          return <div key={o.id} onClick={() => { setScope(o.id); nav('segments'); }} style={{ background: 'var(--paper)', border: '1px solid var(--ink)', padding: '14px 16px 12px', cursor: 'pointer' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span className="u-pixel">{o.tag} · {o.name.toUpperCase()}</span>
              <span className="u-pixel" style={{ background: 'var(--yellow-soft, var(--sage))', padding: '2px 5px' }}>{od}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 8 }}>
              <div style={{ fontSize: 44, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.01em' }}>{h}<span style={{ color: 'var(--ghost-digit)' }}>/5</span></div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 20, fontWeight: 700, lineHeight: 1 }}>{ok.profiles}</div>
                <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>Profiles</div>
              </div>
            </div>
            <div className="u-label" style={{ marginTop: 8 }}>{worstV < 4 ? <HBadge value="!" offset={{ top: 'calc(50% - 7.5px)', right: -22 }}><span>Weakest: {worstL} {worstV}</span></HBadge> : <span>Weakest: {worstL} {worstV}</span>}</div>
          </div>;
        })}
      </div>
    </div>}
    {!owner && <div style={{ background: 'var(--orange)', padding: '22px 24px 24px' }}>
      <div onClick={(e) => { e.stopPropagation(); nav('journey'); }} style={{ cursor: 'pointer' }}>
        <span className="u-pixel">HEALTH PULSE · {D.tag}</span>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginTop: 8 }}>
          <span style={{ fontSize: 72, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.01em' }}>{happy}<span style={{ opacity: 0.4 }}>/5</span></span>
          <span className="u-pixel" style={{ background: 'var(--paper)', padding: '3px 6px' }}>{delta} MO</span>
        </div>
        <div style={{ display: 'flex', gap: 28, marginTop: 16 }}>
          {[['CSAT', k.csat, 'Customer Satisfaction'], ['NPS', k.nps, 'Net Promoter Score'], ['Effort', k.ces, 'Customer Effort Score'], ['Value', k.vfm, 'Value for Money']].map(([l, v, full]) => <div key={l} onClick={v < 4 ? (e) => { e.stopPropagation(); nav('chat', { ask: `${full} is at ${v} for ${D.name} — investigate this poor performance. What's driving it and what should I do first?` }); } : undefined} style={v < 4 ? { cursor: 'pointer' } : null}>
            <HBadge value={v < 4 ? '!' : undefined} offset={{ top: -6, right: -14 }}><div style={{ fontSize: 22, fontWeight: 700, lineHeight: 1 }}>{v}</div></HBadge>
            <div className="u-label" style={{ color: 'var(--ink)', opacity: 0.6, marginTop: 4 }}>{l}</div>
          </div>)}
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 28 }}>
        <span className="u-pixel">YOUR CUSTOMERS</span>
        <span className="u-label" style={{ color: 'var(--ink)', opacity: 0.6 }}>{k.profiles} profiles · {D.segments.length} segments</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 12 }}>
        {(() => {
          const worst = [...D.segments].sort((a, b) => (a.csat + a.nps + a.ces + a.vfm) - (b.csat + b.nps + b.ces + b.vfm)).slice(0, 2).map(s => s.id);
          return D.segments.map(s => {
          const alert = worst.includes(s.id);
          return <div key={s.id} onClick={() => nav('segment', s.id)} style={{ background: 'var(--paper)', border: '1px solid var(--ink)', padding: '12px 8px 10px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
            <HBadge value={alert ? '!' : undefined}><MoodChar seg={s} size={44} /></HBadge>
            <span className="u-label" style={{ color: 'var(--ink)', textAlign: 'center' }}>{s.label.split(' ')[0].replace('-hour', '')}</span>
            <span className="u-label" style={{ color: 'var(--ink)', opacity: 0.6 }}>{s.count} · {s.pct}%</span>
          </div>;
        });
        })()}
      </div>
    </div>}
    <div style={{ background: 'var(--orange)', flex: 1 }}></div>
  </div>;
}

Object.assign(window, { HomeScreen });
