const DSs = window.RallyAIBusiness_2d8789;
const { PixelIcon: SIcon, PixelChar: SChar, StatBig: SStat, StatCard: SCard, MeterBar: SMeter, BarcodeChart: SBar, ListRow: SRow, Button: SButton, Chip: SChip } = DSs;

function moodOf(csat) { return csat >= 4.3 ? 'happy' : csat >= 3.9 ? 'neutral' : 'sad'; }
const CHAR_PHOTO = { bun: 'tastey', cat: 'trendo', rabbit: 'dash', blob: 'mingle', sprout: 'sprig', gift: 'boxie', octo: 'otto', chick: 'pip' };
function MoodChar({ seg, size, fill }) {
  const mood = moodOf(seg.csat);
  const photos = (window.RallyTweaks || {}).avatarStyle === 'photo';
  if (photos) return <span title={mood + ' · CSAT ' + seg.csat} style={{ display: fill ? 'block' : 'inline-flex', position: 'relative', width: fill ? '100%' : undefined }}>
    <img src={'assets/photos/segments/' + CHAR_PHOTO[seg.char] + '.png'} width={fill ? undefined : size} height={fill ? undefined : size} style={{ display: 'block', objectFit: 'cover', border: fill ? 'none' : '1px solid var(--ink)', width: fill ? '100%' : size, aspectRatio: '1' }} alt={seg.label} />
  </span>;
  return <span className={'mood-' + mood} title={mood + ' · CSAT ' + seg.csat} style={{ display: 'inline-flex' }}><SChar name={seg.char} size={size} /></span>;
}

function SegmentsScreen({ D, nav }) {
  return <div style={{ '--accent': 'var(--yellow)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 16px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Segments</h1>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>{D.name} · {D.kpis.profiles} profiles · {D.segments.length} segments</div>
    </div>
    <div style={{ background: 'var(--sage)', flex: 1, padding: '20px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignContent: 'start' }}>
      {D.segments.map(s => {
        const photos = (window.RallyTweaks || {}).avatarStyle === 'photo';
        return <div key={s.id} onClick={() => nav('segment', s.id)} style={{ border: '1px solid var(--ink)', padding: photos ? 0 : '14px 12px 0', cursor: 'pointer', background: 'var(--paper)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 0, textAlign: 'center' }}>
        <MoodChar seg={s} size={64} fill={photos} />
        <div style={{ padding: '10px 12px 14px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: '100%', boxSizing: 'border-box' }}>
        <div style={{ fontSize: 15, fontWeight: 700, lineHeight: 1.1 }}>{s.label}</div>
        <div style={{ fontSize: 20, fontWeight: 700 }}>{((s.csat + s.nps + s.ces + s.vfm) / 4).toFixed(1)}<span style={{ color: 'var(--ghost-digit)' }}>/5</span></div>
        <div className="u-label" style={{ color: 'var(--text-muted)' }}>{s.count} profiles<br></br>{s.pct}%</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 2, width: '100%', borderTop: '1px solid rgba(32,36,27,.2)', paddingTop: 8 }}>
          {[['CSAT', s.csat], ['NPS', s.nps], ['CES', s.ces], ['VFM', s.vfm]].map(([l, v]) => <div key={l}>
            <div style={{ fontSize: 13, fontWeight: 700, background: v < 4 ? 'var(--accent)' : 'transparent', padding: '1px 0' }}>{v}</div>
            <div className="u-label" style={{ fontSize: 9, color: 'var(--text-muted)', marginTop: 2 }}>{l}</div>
          </div>)}
        </div>
        </div>
      </div>;
      })}
    </div>
    <div onClick={() => nav('compare')} style={{ background: 'var(--paper)', borderTop: '1px solid var(--ink)', padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}>
      <div><div style={{ fontSize: 16, fontWeight: 700 }}>Compare outlets</div><div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>Great World vs Raffles Place</div></div>
      <SIcon name="chart" size={24} />
    </div>
  </div>;
}

function DetailSection({ title, sub, defaultOpen = false, children }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return <div style={{ borderTop: '1px solid var(--ink)' }}>
    <div onClick={() => setOpen(o => !o)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 24px', cursor: 'pointer' }}>
      <div>
        <span style={{ fontSize: 16, fontWeight: 700 }}>{title}</span>
        {sub && <span className="u-label" style={{ color: 'var(--text-muted)', marginLeft: 10 }}>{sub}</span>}
      </div>
      <SIcon name="arrow-right" size={14} style={{ transform: open ? 'rotate(-90deg)' : 'rotate(90deg)', transition: 'transform 120ms var(--ease-snap)' }} />
    </div>
    {open && <div style={{ padding: '0 24px 18px' }}>{children}</div>}
  </div>;
}

function SegmentDetailScreen({ D, id, nav }) {
  const s = D.segments.find(x => x.id === id) || D.segments[0];
  const days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
  return <div style={{ '--accent': 'var(--yellow)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ background: 'var(--paper)', borderBottom: '1px solid var(--ink)', padding: '16px 24px 20px' }}>
      <div onClick={() => nav('segments')} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginBottom: 14 }}>
        <SIcon name="arrow-right" size={14} style={{ transform: 'scaleX(-1)' }} /><span className="u-label">Segments · {D.name}</span>
      </div>
      <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
        <MoodChar seg={s} size={96} />
        <div>
          <SChip pixel>{s.count} profiles · {s.pct}%</SChip>
          <h1 style={{ fontSize: 'var(--text-title)', marginTop: 8 }}>{s.label}</h1>
          <p style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4, textWrap: 'pretty' }}>{s.desc}</p>
        </div>
      </div>
    </div>
    <div style={{ padding: '20px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      <SCard value={'$' + s.avgSpend} label="Avg spend" delta="+4%" period="MO" />
      <SCard value={'$' + Math.round(s.avgSpend * (s.days.reduce((a, b) => a + b, 0) / s.count) * 12)} label="LTV · 12 mo" delta="+2%" period="MO" />
      <SCard value={s.peakDay.slice(0, 3)} label="Peak day" />
      <SCard value={String(s.items)} label="Avg items" delta="-1%" period="MO" />
    </div>
    <div style={{ padding: '0 24px 16px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', alignItems: 'end', height: 56 }}>
        {s.days.map((v, i) => {
          const mx = Math.max(...s.days, 1), strong = v === Math.max(...s.days);
          return <div key={i} style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-end', height: '100%' }}>
            <div style={{ width: 8, height: Math.max(2, Math.round(v / mx * 56)), background: strong ? 'var(--ink)' : 'var(--chart-line)' }}></div>
          </div>;
        })}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', marginTop: 6 }}>
        {days.map((d, i) => <span key={i} className="u-label" style={{ color: 'var(--text-muted)', textAlign: 'center' }}>{d}</span>)}
      </div>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 10 }}>Visits by day of week · last 30 days</div>
    </div>
    <div style={{ background: 'var(--moss)', color: 'var(--white)', padding: '16px 24px', display: 'grid', gap: 12 }}>
      <span className="u-pixel">Vibe check</span>
      <div style={{ '--ink': 'var(--white)', '--text-muted': 'rgba(239,240,233,.6)', display: 'grid', gap: 10 }}>
        <SMeter label="Customer Satisfaction Score" value={s.csat} /><SMeter label="Net Promoter Score" value={s.nps} /><SMeter label="Customer Effort Score" value={s.ces} /><SMeter label="Value for Money" value={s.vfm} accent />
      </div>
    </div>
    <div style={{ flex: 1 }}>
      {s.demo && <DetailSection title="Age" sub={s.demo.est ? 'EST' : undefined} defaultOpen>
        <div style={{ display: 'flex', gap: 32 }}>
          <SStat value={String(s.demo.age)} label="Avg age" size="title" />
          <SStat value={s.demo.range[0] + '–' + s.demo.range[1]} label="Age range" size="title" />
        </div>
        {(() => {
          const [lo, hi] = s.demo.range, mean = s.demo.age, sig = Math.max(6, (hi - lo) / 4);
          const buckets = [['18–24', 18, 24], ['25–34', 25, 34], ['35–44', 35, 44], ['45–54', 45, 54], ['55+', 55, 80]];
          const ws = buckets.map(([l, a, b]) => (b < lo || a > hi) ? 0 : Math.exp(-Math.pow(((a + Math.min(b, hi)) / 2 - mean) / sig, 2) / 2));
          const total = ws.reduce((x, y) => x + y, 0), mx = Math.max(...ws);
          return <div style={{ marginTop: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', alignItems: 'end', height: 48, gap: 8 }}>
              {ws.map((w, i) => <div key={i} style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-end', height: '100%' }}>
                <div style={{ width: '100%', height: Math.max(2, Math.round(w / mx * 48)), background: w === mx ? 'var(--ink)' : 'var(--chart-line)' }}></div>
              </div>)}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', marginTop: 6, gap: 8 }}>
              {buckets.map(([l], i) => <span key={i} className="u-label" style={{ color: 'var(--text-muted)', textAlign: 'center' }}>{l}</span>)}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', marginTop: 2, gap: 8 }}>
              {ws.map((w, i) => <span key={i} className="u-label" style={{ color: 'var(--ink)', textAlign: 'center' }}>{total ? Math.round(w / total * 100) : 0}%</span>)}
            </div>
            <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 10 }}>Age distribution · estimated from quest responses</div>
          </div>;
        })()}
      </DetailSection>}
      {s.demo && <DetailSection title="Gender" sub={s.demo.est ? 'EST' : undefined}>
        <div style={{ display: 'grid', gap: 8 }}>
          {s.demo.gender.map(([g, c]) => <SMeter key={g} label={g} value={c} max={s.count} display={Math.round(c / s.count * 100) + '%'} />)}
        </div>
      </DetailSection>}
      {s.slots && <DetailSection title="Visit times">
        <div style={{ display: 'grid', gap: 8 }}>
          {s.slots.map(([sl, c]) => <SMeter key={sl} label={sl} value={c} max={Math.max(...s.slots.map(x => x[1]))} display={c} />)}
        </div>
      </DetailSection>}
      {(() => {
        const visits = s.days.reduce((a, b) => a + b, 0) / s.count;
        const rec = Math.max(1, Math.round(30 / Math.max(visits, 0.5) / 2));
        return <DetailSection title="RFM" sub="EST">
          <div style={{ display: 'flex', gap: 32 }}>
            <SStat value={rec + 'd'} label="Recency" size="title" />
            <SStat value={visits.toFixed(1) + '/mo'} label="Frequency" size="title" />
            <SStat value={'$' + Math.round(s.avgSpend * visits * 12)} label="Monetary · yr" size="title" />
          </div>
          <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 12 }}>Avg last-visit gap · visits per month · spend per customer per year</div>
        </DetailSection>;
      })()}
      <DetailSection title="Acquisition channels">
        {s.channels.map(([name, count], i) => <SRow key={i} label={<span style={{ fontSize: 16 }}>{name}</span>} value={count} style={i === s.channels.length - 1 ? { borderBottom: 'none' } : null} />)}
      </DetailSection>
    </div>
    <div style={{ background: 'var(--accent)' }}>
      <SButton full size="lg" variant="accent" onClick={() => nav('journey', { seg: s.id })} style={{ border: 'none', borderBottom: '1px solid var(--ink)', justifyContent: 'space-between' }}>View journey map <SIcon name="journey" size={16} /></SButton>
      <SButton full size="lg" variant="accent" onClick={() => nav('questNew', { seg: s.label })} style={{ border: 'none', justifyContent: 'space-between' }}>Quest this segment <SIcon name="arrow-up-right" size={16} /></SButton>
    </div>
  </div>;
}

function CompareScreen({ nav }) {
  const A = RallyData.outlets.flagship, B = RallyData.outlets.kiosk;
  const money = v => '$' + v.toFixed(2);
  const rows = [
    ['Profiles', A.kpis.profiles, B.kpis.profiles],
    ['Recency', '9d', '6d', 'Recency — average days since a customer\'s last visit. Lower is better. Estimated from quest check-ins.', true],
    ['Frequency', (A.segments.reduce((t, s) => t + s.days.reduce((a, b) => a + b, 0), 0) / A.kpis.profiles).toFixed(1) + '/mo', (B.segments.reduce((t, s) => t + s.days.reduce((a, b) => a + b, 0), 0) / B.kpis.profiles).toFixed(1) + '/mo', 'Frequency — average visits per customer per month, from the last 30 days of responses.'],
    ['Monetary · yr', '$' + Math.round(A.kpis.spend * (A.segments.reduce((t, s) => t + s.days.reduce((a, b) => a + b, 0), 0) / A.kpis.profiles) * 12), '$' + Math.round(B.kpis.spend * (B.segments.reduce((t, s) => t + s.days.reduce((a, b) => a + b, 0), 0) / B.kpis.profiles) * 12), 'Monetary — average spend per customer across a year: avg ticket × visit frequency × 12. Estimated.'],
    ['CES', A.kpis.ces, B.kpis.ces, 'Customer Effort Score — how easy it is to order and pay. Higher is smoother.'],
    ['CSAT', A.kpis.csat, B.kpis.csat, 'Customer Satisfaction Score — how happy customers are with the product experience.'],
    ['NPS', A.kpis.nps, B.kpis.nps, 'Net Promoter Score — how likely customers are to recommend you to others.'],
    ['VFM', A.kpis.vfm, B.kpis.vfm, 'Value for Money — whether the price feels worth it. Your weakest metric brand-wide.'],
    ['Responses\ntoday', A.today, B.today],
  ];
  return <div style={{ '--accent': 'var(--yellow)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 16px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Compare</h1>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>Two outlets · side by side</div>
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr', borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)' }}>
      <div style={{ padding: '14px 0 14px 24px' }}></div>
      {[A, B].map(o => <div key={o.id} style={{ padding: '14px 12px', borderLeft: '1px solid var(--ink)' }}>
        <div className="u-pixel">{o.tag}</div>
        <div style={{ fontSize: 15, fontWeight: 700, marginTop: 4 }}>{o.name}</div>
        <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{o.sub.split(' · ')[0]}</div>
      </div>)}
      {rows.map(([l, a, b, info, invert], i) => {
        let hiA = parseFloat(a) > parseFloat(b), hiB = parseFloat(b) > parseFloat(a);
        if (invert) { const t2 = hiA; hiA = hiB; hiB = t2; }
        return <React.Fragment key={i}>
          <div style={{ padding: '12px 0 12px 24px', borderTop: '1px solid var(--ink)', fontSize: 14, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'pre-line' }}>{l}{info && <span onClick={() => window.dispatchEvent(new CustomEvent('rallyExplain', { detail: info }))} style={{ cursor: 'pointer', width: 15, height: 15, border: '1px solid var(--ink)', borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, flexShrink: 0 }}>i</span>}</div>
          <div style={{ padding: '12px', borderTop: '1px solid var(--ink)', borderLeft: '1px solid var(--ink)', fontSize: 20, fontWeight: 700, background: hiA ? 'var(--sage)' : 'transparent' }}>{a}</div>
          <div style={{ padding: '12px', borderTop: '1px solid var(--ink)', borderLeft: '1px solid var(--ink)', fontSize: 20, fontWeight: 700, background: hiB ? 'var(--sage)' : 'transparent' }}>{b}</div>
        </React.Fragment>;
      })}
    </div>
    <div style={{ background: 'var(--sage)', padding: '16px 24px 20px', flex: 1 }}>
      <span className="u-label" style={{ color: 'var(--text-muted)' }}>Segment mix</span>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 12 }}>
        {[A, B].map(o => <div key={o.id} style={{ display: 'grid', gap: 8, alignContent: 'start', gridAutoRows: 'min-content' }}>
          <span className="u-pixel">{o.tag} · {o.kpis.profiles} PROFILES</span>
          {o.segments.map(s => <div key={s.id} style={{ display: 'grid', gridTemplateRows: '26px 8px', gap: 6 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 6, minWidth: 0 }}>
              <span className="u-label" style={{ color: 'var(--text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.label}</span>
              <span style={{ fontSize: 'var(--text-small)', fontWeight: 700, flexShrink: 0 }}>{s.pct}%</span>
            </div>
            <div style={{ border: '1px solid var(--ink)', boxSizing: 'border-box' }}>
              <div style={{ height: '100%', width: Math.min(100, s.pct / 50 * 100) + '%', background: 'var(--ink)' }}></div>
            </div>
          </div>)}
        </div>)}
      </div>
    </div>
    <div style={{ background: 'var(--accent)' }}>
      <SButton full size="lg" variant="accent" onClick={() => nav('chat')} style={{ border: 'none', justifyContent: 'space-between' }}>Ask RALLY about the gap <SIcon name="arrow-up-right" size={16} /></SButton>
    </div>
  </div>;
}

Object.assign(window, { SegmentsScreen, SegmentDetailScreen, CompareScreen, MoodChar, moodOf });
