const DSq = window.RallyAIBusiness_2d8789;
const { PixelIcon: QIcon, PixelChar: QChar, ListRow: QRow, StatBig: QStat, Chip: QChip, Toggle: QToggle, Button: QButton, BarcodeChart: QBar, QuestSet: QSet, Input: QInput } = DSq;

function scrubDate(i) { const d = new Date(); d.setDate(d.getDate() - (29 - i)); return d.getDate() + '-' + d.toLocaleString('en', { month: 'short' }); }

function ResponseScrubber({ data, sel, setSel }) {
  const slot = 14, H = 56;
  const ref = React.useRef(null);
  const [w, setW] = React.useState(342);
  React.useEffect(() => { if (ref.current) setW(ref.current.offsetWidth); }, []);
  const max = Math.max(...data, 1);
  const drag = React.useRef(null);
  const clamp = i => Math.max(0, Math.min(data.length - 1, i));
  return <div style={{ marginTop: 14 }}>
    <div ref={ref}
      onPointerDown={e => { drag.current = { x: e.clientX, sel }; e.currentTarget.setPointerCapture(e.pointerId); }}
      onPointerMove={e => { if (drag.current) setSel(clamp(drag.current.sel + Math.round((drag.current.x - e.clientX) / slot))); }}
      onPointerUp={() => { drag.current = null; }}
      onWheel={e => setSel(s => clamp(s + Math.sign(e.deltaX || e.deltaY)))}
      style={{ overflow: 'hidden', touchAction: 'none', cursor: 'grab', position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', height: H, transform: `translateX(${w / 2 - (sel + 0.5) * slot}px)`, transition: drag.current ? 'none' : 'transform 160ms var(--ease-snap)' }}>
        {data.map((v, i) => <div key={i} onClick={() => setSel(i)} style={{ width: slot, height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'flex-end', flexShrink: 0, cursor: 'pointer' }}>
          <div style={{ width: i === sel ? slot : 6, height: Math.max(3, Math.round(v / max * H)), background: i === sel ? 'var(--accent)' : 'rgba(32,36,27,.4)', transition: 'width 160ms var(--ease-snap)' }}></div>
        </div>)}
      </div>
      <div style={{ position: 'absolute', left: '50%', top: 0, bottom: 0, width: 1, background: 'rgba(32,36,27,.25)', pointerEvents: 'none' }}></div>
    </div>
    <div className="u-label" style={{ color: 'var(--text-muted)', textAlign: 'center', marginTop: 6 }}>{scrubDate(sel)}</div>
  </div>;
}

function QuestsScreen({ D, scopeId, quests, nav }) {
  const [auto, setAuto] = React.useState(true);
  const [sel, setSel] = React.useState(29);
  React.useEffect(() => setSel(29), [scopeId]);
  const live = quests.filter(q => q.status === 'Live');
  return <div style={{ '--accent': 'var(--orange)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 20px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Quests</h1>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 6 }}>{D.name}</div>
      <div style={{ display: 'flex', gap: 40, marginTop: 14 }}>
        <QStat value={String(D.responsesByDay[sel])} label="Responses" size="title" />
      </div>
      <ResponseScrubber data={D.responsesByDay} sel={sel} setSel={setSel} />
    </div>
    <div style={{ background: 'var(--sage)', padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div><div style={{ fontSize: 18, fontWeight: 700 }}>{auto ? 'Auto mode' : 'Manual mode'}</div>
        <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{auto ? 'RALLY runs the question sets for you' : 'Pick question sets from the library'}</div></div>
      <QToggle checked={auto} onChange={setAuto} />
    </div>
    <div style={{ padding: '8px 24px 4px', flex: 1 }}>
      {quests.map((q, i) => <QRow key={i} icon={<QIcon name="quest" />} label={q.title}
        sublabel={`${q.o ? q.o + ' · ' : ''}${q.mode} · ${q.questions} questions · ${q.responses} responses`}
        value={<QChip pixel variant={q.status === 'Live' ? 'accent' : q.status === 'Done' ? 'fill' : 'outline'}>{q.status}</QChip>} onClick={() => {}} />)}
      <div style={{ padding: '16px 0' }}>
        {auto
          ? <div onClick={() => nav('library')} style={{ background: 'var(--accent)', border: '1px solid var(--ink)', padding: '16px', display: 'flex', gap: 14, alignItems: 'center', cursor: 'pointer' }}>
              <QIcon name="library" size={36} />
              <div>
                <div style={{ fontSize: 16, fontWeight: 700 }}>Quest Library</div>
                <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 4 }}>Consultant question sets · nothing to configure</div>
              </div>
            </div>
          : <div>
              <div className="u-label" style={{ color: 'var(--text-muted)', marginBottom: 12 }}>Question library · {RallyData.library.length} sets · by objective · read-only</div>
              <div style={{ display: 'grid', gap: 10 }}>
                {RallyData.library.map((l, i) => <QSet key={i} objective={l.objective} title={l.title} count={l.count} />)}
              </div>
            </div>}
      </div>
    </div>
    <div style={{ background: 'var(--paper)', borderTop: '1px solid var(--ink)' }}>
      <QButton full size="lg" variant="ghost" onClick={() => nav('questNew')} style={{ border: 'none', justifyContent: 'space-between' }}>Start new quest <QIcon name="arrow-up-right" size={16} /></QButton>
    </div>
  </div>;
}

function LibraryScreen({ nav }) {
  const [q, setQ] = React.useState('');
  const list = RallyData.library.filter(l => !q.trim() || (l.objective + ' ' + l.title).toLowerCase().includes(q.trim().toLowerCase()));
  return <div style={{ '--accent': 'var(--orange)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '14px 24px', borderBottom: '1px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <h1 style={{ fontSize: 'var(--text-title)' }}>Quest Library</h1>
      <span onClick={() => nav('quests')} style={{ cursor: 'pointer', display: 'inline-flex' }}><QIcon name="close" size={18} /></span>
    </div>
    <div style={{ padding: '14px 24px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
      <QIcon name="search" size={18} style={{ flexShrink: 0 }} />
      <QInput placeholder="Search objectives" value={q} onChange={e => setQ(e.target.value)} style={{ flex: 1 }} />
    </div>
    <div style={{ flex: 1, padding: '16px 24px 24px' }}>
      <div className="u-label" style={{ color: 'var(--text-muted)', marginBottom: 12 }}>{list.length} sets · by objective · read-only</div>
      <div style={{ display: 'grid', gap: 10 }}>
        {list.map((l, i) => <QSet key={i} objective={l.objective} title={l.title} count={l.count} />)}
        {list.length === 0 && <div className="u-label" style={{ color: 'var(--text-muted)' }}>No sets match “{q}”</div>}
      </div>
    </div>
  </div>;
}

function QuestNewScreen({ scopeId, preSeg, onLaunch, nav }) {
  const [outlet, setOutlet] = React.useState(scopeId === 'brand' ? 'flagship' : scopeId);
  const [set, setSet] = React.useState(1);
  const [name, setName] = React.useState('');
  const [target, setTarget] = React.useState(preSeg || 'All customers');
  const [auto, setAuto] = React.useState(true);
  const O = RallyData.outlets[outlet];
  const lib = RallyData.library;
  const launch = () => {
    onLaunch(outlet, { title: name.trim() || lib[set].title, status: 'Live', mode: auto ? 'Auto' : 'Manual', responses: 0, questions: lib[set].count, target });
    nav('quests');
  };
  const pill = (on) => ({ display: 'inline-flex', alignItems: 'center', gap: 8, border: '1px solid var(--ink)', padding: '8px 12px', cursor: 'pointer', fontSize: 13, fontWeight: 500, background: on ? 'var(--ink)' : 'transparent', color: on ? 'var(--white)' : 'var(--ink)', transition: 'background 120ms var(--ease-snap)' });
  return <div style={{ '--accent': 'var(--orange)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '16px 24px 14px', borderBottom: '1px solid var(--ink)' }}>
      <div onClick={() => nav('quests')} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', marginBottom: 10 }}>
        <QIcon name="arrow-right" size={14} style={{ transform: 'scaleX(-1)' }} /><span className="u-label">Quests</span>
      </div>
      <h1 style={{ fontSize: 'var(--text-title)' }}>New quest</h1>
    </div>
    <div style={{ flex: 1, padding: '18px 24px 24px', display: 'grid', gap: 22, alignContent: 'start' }}>
      {scopeId === 'brand' && <div>
        <span className="u-label" style={{ color: 'var(--text-muted)' }}>01 · Outlet</span>
        <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
          {Object.values(RallyData.outlets).map(o => <span key={o.id} onClick={() => { setOutlet(o.id); setTarget('All customers'); }} style={pill(outlet === o.id)}>{o.name}</span>)}
        </div>
      </div>}
      <div>
        <span className="u-label" style={{ color: 'var(--text-muted)' }}>{scopeId === 'brand' ? '02' : '01'} · Question set</span>
        <div style={{ display: 'grid', gap: 10, marginTop: 10 }}>
          {lib.map((l, i) => <QSet key={i} objective={l.objective} title={l.title} count={l.count} selected={set === i} onUse={() => setSet(i)} />)}
        </div>
      </div>
      <div>
        <span className="u-label" style={{ color: 'var(--text-muted)' }}>{scopeId === 'brand' ? '03' : '02'} · Target segment</span>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
          <span onClick={() => setTarget('All customers')} style={pill(target === 'All customers')}>All customers</span>
          {O.segments.map(s => <span key={s.id} onClick={() => setTarget(s.label)} style={pill(target === s.label)}><QChar name={s.char} size={20} />{s.label}</span>)}
        </div>
      </div>
      <div>
        <span className="u-label" style={{ color: 'var(--text-muted)' }}>{scopeId === 'brand' ? '04' : '03'} · Name & mode</span>
        <QInput placeholder={lib[set].title} value={name} onChange={e => setName(e.target.value)} style={{ marginTop: 10, width: '100%' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
          <div><div style={{ fontSize: 15, fontWeight: 700 }}>{auto ? 'Auto mode' : 'Manual mode'}</div>
            <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{auto ? 'RALLY schedules and rotates questions' : 'You control the question order'}</div></div>
          <QToggle checked={auto} onChange={setAuto} />
        </div>
      </div>
    </div>
    <div style={{ background: 'var(--accent)' }}>
      <QButton full size="lg" variant="accent" onClick={launch} style={{ border: 'none', justifyContent: 'space-between' }}>Launch quest · {RallyData.outlets[outlet].tag} <QIcon name="arrow-up-right" size={16} /></QButton>
    </div>
  </div>;
}

Object.assign(window, { QuestsScreen, QuestNewScreen, LibraryScreen });
