const DSx = window.RallyAIBusiness_2d8789;
const { PixelIcon: XIcon, Button: XButton, RallyFace: XFace, SpeechBox: XSpeech } = DSx;
DSx.ICON_GRIDS['bell'] = ['................', '.......##.......', '......####......', '.....######.....', '.....######.....', '....########....', '....########....', '....########....', '....########....', '...##########...', '...##########...', '..############..', '................', '......####......', '.......##.......', '................'];

const NOTIFS = {
  brand: [
    { icon: 'quest', t: '21 new quest responses today across both outlets.', v: 'quests' },
    { icon: 'send', t: 'Wei Lin replied about the new packaging box.', v: 'thread', a: 'weilin' },
    { icon: 'alert', t: 'Kiosk temperature complaints passed 40% — journey flag raised.', v: 'journey', a: 3 },
  ],
  flagship: [
    { icon: 'quest', t: '12 new responses on Weekend regulars.', v: 'quests' },
    { icon: 'send', t: 'Wei Lin replied about the new packaging box.', v: 'thread', a: 'weilin' },
    { icon: 'alert', t: 'Retention VFM still weakest stage — 64% want loyalty.', v: 'journey', a: 4 },
  ],
  kiosk: [
    { icon: 'quest', t: '9 new responses on Morning rush pulse.', v: 'quests' },
    { icon: 'send', t: 'Kelvin asked about opening before 8am.', v: 'thread', a: 'kelvin' },
    { icon: 'alert', t: 'Temperature flagged by 42% at Consumption.', v: 'journey', a: 3 },
  ],
};

const NAV = [
  ['home', 'home', 'Home'],
  ['segments', 'segments', 'Segments'],
  ['quests', 'quest', 'Quests'],
  ['messages', 'chat', 'Chats'],
  ['chat', 'face', 'Rally'],
];
const SCOPES = ['brand', 'flagship', 'kiosk'];

function StatusRow({ nav, onBell, unread }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 24px 10px', flexShrink: 0 }}>
    <img src="assets/logo.png" style={{ height: 14, display: 'block' }} alt="RALLY!" />
    <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
      <span onClick={onBell} style={{ cursor: 'pointer', display: 'flex', position: 'relative' }}>
        <XIcon name="bell" size={22} />
        {unread > 0 && <span style={{ position: 'absolute', top: -2, right: -4, width: 8, height: 8, background: 'var(--orange)', border: '1px solid var(--ink)' }}></span>}
      </span>
      <span onClick={() => nav('account')} style={{ cursor: 'pointer', width: 24, height: 24, background: 'var(--ink)', color: 'var(--white)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 10 }}>JT</span>
    </div>
  </div>;
}

function NotifSheet({ scopeId, onClose, nav }) {
  const list = NOTIFS[scopeId] || NOTIFS.brand;
  return <div style={{ position: 'absolute', left: 0, right: 0, top: 0, background: 'var(--paper)', borderBottom: '1px solid var(--ink)', zIndex: 10, boxShadow: '0 8px 0 rgba(32,36,27,.12)' }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px 10px' }}>
      <span className="u-pixel">NOTIFICATIONS</span>
      <span onClick={onClose} style={{ cursor: 'pointer', display: 'flex' }}><XIcon name="close" size={18} /></span>
    </div>
    {list.map((n, i) => <div key={i} onClick={() => { onClose(); nav(n.v, n.a); }} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '12px 24px', borderTop: '1px solid rgba(32,36,27,.2)', cursor: 'pointer' }}>
      <XIcon name={n.icon} size={18} style={{ flexShrink: 0, marginTop: 1 }} />
      <span style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.35, flex: 1 }}>{n.t}</span>
      <XIcon name="arrow-right" size={12} style={{ flexShrink: 0, marginTop: 3 }} />
    </div>)}
  </div>;
}

function Switcher({ scopeId, setScope, open, setOpen, nav }) {
  const cur = RallyData.scope(scopeId);
  return <div style={{ borderBottom: '1px solid var(--ink)', flexShrink: 0, background: 'var(--paper)' }}>
    <div onClick={() => setOpen(!open)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 24px 10px', cursor: 'pointer' }}>
      <span className="u-pixel">{cur.tag}</span>
      <span style={{ fontSize: 16, fontWeight: 700, flex: 1 }}>Shiok Pun · {cur.name}</span>
      <XIcon name="arrow-right" size={14} style={{ transform: open ? 'rotate(-90deg)' : 'rotate(90deg)', transition: 'transform 120ms var(--ease-snap)' }} />
    </div>
    {open && <div style={{ borderTop: '1px solid rgba(32,36,27,.2)' }}>
      {SCOPES.map(id => {
        const o = RallyData.scope(id), on = id === scopeId;
        return <div key={id} onClick={() => { setScope(id); setOpen(false); }} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 24px', cursor: 'pointer', background: on ? 'var(--ink)' : 'transparent', color: on ? 'var(--white)' : 'var(--ink)', borderBottom: '1px solid rgba(32,36,27,.2)' }}>
          <span className="u-pixel" style={{ width: 30 }}>{o.tag}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>{o.name}</div>
            <div className="u-label" style={{ color: on ? 'rgba(239,240,233,.6)' : 'var(--text-muted)', marginTop: 1 }}>{o.sub}</div>
          </div>
          <span style={{ fontSize: 15, fontWeight: 700 }}>{o.kpis.profiles}</span>
        </div>;
      })}
      <div onClick={() => { setOpen(false); nav('compare'); }} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 24px', cursor: 'pointer' }}>
        <XIcon name="chart" size={20} />
        <span style={{ fontSize: 15, fontWeight: 700 }}>Compare outlets</span>
      </div>
    </div>}
  </div>;
}

function AccountScreen({ email, onSignOut, userMode, setUserMode, avatarStyle, setAvatarStyle }) {
  const rows = [
    ['settings', 'Business profile', 'Shiok Pun · 2 outlets'],
    ['bell', 'Notifications', 'Insights, replies & journey flags'],
    ['segments', 'Team access', 'Only you · invite staff'],
    ['library', 'Data & privacy', 'Customer permissions · export'],
  ];
  return <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ padding: '20px 24px 16px' }}>
      <h1 style={{ fontSize: 'var(--text-display)' }}>Account (demo)</h1>
    </div>
    <div style={{ background: 'var(--sage)', padding: '18px 24px', display: 'flex', alignItems: 'center', gap: 14 }}>
      <span style={{ width: 52, height: 52, background: 'var(--ink)', color: 'var(--white)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 18, flexShrink: 0 }}>JT</span>
      <div>
        <div style={{ fontSize: 18, fontWeight: 700 }}>Jamie Tan</div>
        <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{email} · signed in with Google</div>
      </div>
    </div>
    <div style={{ flex: 1, padding: '8px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 0', borderBottom: '1px solid rgba(32,36,27,.2)' }}>
        <XIcon name="manual" size={20} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700 }}>Role</div>
          <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{userMode === 'owner' ? 'Owner · all outlets' : 'Outlet manager · single outlet'}</div>
        </div>
        <div style={{ display: 'flex' }}>
          {['owner', 'manager'].map(m => <span key={m} onClick={() => setUserMode(m)} style={{ border: '1px solid var(--ink)', marginLeft: -1, padding: '6px 10px', cursor: 'pointer', fontSize: 12, fontWeight: 500, textTransform: 'capitalize', background: userMode === m ? 'var(--ink)' : 'transparent', color: userMode === m ? 'var(--white)' : 'var(--ink)' }}>{m}</span>)}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 0', borderBottom: '1px solid rgba(32,36,27,.2)' }}>
        <XIcon name="segments" size={20} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700 }}>Segment avatars</div>
          <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{avatarStyle === 'photo' ? 'Real customer photos' : 'Pixel mascots'}</div>
        </div>
        <div style={{ display: 'flex' }}>
          {['mascot', 'photo'].map(m => <span key={m} onClick={() => setAvatarStyle(m)} style={{ border: '1px solid var(--ink)', marginLeft: -1, padding: '6px 10px', cursor: 'pointer', fontSize: 12, fontWeight: 500, textTransform: 'capitalize', background: avatarStyle === m ? 'var(--ink)' : 'transparent', color: avatarStyle === m ? 'var(--white)' : 'var(--ink)' }}>{m}</span>)}
        </div>
      </div>
      {rows.map(([icon, label, sub], i) => <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 0', borderBottom: '1px solid rgba(32,36,27,.2)' }}>
        <XIcon name={icon} size={20} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700 }}>{label}</div>
          <div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>
        </div>
        <XIcon name="arrow-right" size={14} />
      </div>)}
    </div>
    <div style={{ background: 'var(--sage)' }}>
      <XButton full size="lg" variant="ghost" onClick={onSignOut} style={{ border: 'none', justifyContent: 'space-between' }}>Sign out <XIcon name="arrow-up-right" size={16} /></XButton>
    </div>
  </div>;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "userMode": "owner",
  "avatarStyle": "mascot"
}/*EDITMODE-END*/;

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  window.RallyTweaks = tw;
  const userMode = tw.userMode;
  const [session, setSession] = React.useState(() => localStorage.getItem('sp_session'));
  const [scopeId, setScopeIdRaw] = React.useState(() => localStorage.getItem('sp_scope') || 'brand');
  const [route, setRoute] = React.useState(() => { try { return JSON.parse(localStorage.getItem('sp_route')) || { v: 'home' }; } catch (e) { return { v: 'home' }; } });
  const [switcherOpen, setSwitcherOpen] = React.useState(false);
  const [notifs, setNotifs] = React.useState(false);
  const [explain, setExplain] = React.useState(null);
  React.useEffect(() => {
    const h = (e) => setExplain(e.detail);
    window.addEventListener('rallyExplain', h);
    return () => window.removeEventListener('rallyExplain', h);
  }, []);
  const [seen, setSeen] = React.useState(false);
  const [quests, setQuests] = React.useState(() => ({ flagship: [...RallyData.outlets.flagship.quests], kiosk: [...RallyData.outlets.kiosk.quests] }));
  const [custs, setCusts] = React.useState(() => RallyData.customers.map(c => ({ ...c, msgs: [...c.msgs] })));
  React.useEffect(() => { localStorage.setItem('sp_scope', scopeId); }, [scopeId]);
  React.useEffect(() => { localStorage.setItem('sp_route', JSON.stringify(route)); }, [route]);
  const nav = (v, a) => { setSwitcherOpen(false); setNotifs(false); setRoute({ v, a }); };
  const setScope = (id) => { setScopeIdRaw(id); if (route.v === 'segment' || route.v === 'thread') setRoute({ v: route.v === 'segment' ? 'segments' : 'messages' }); };
  if (!session) return <Frame><LoginScreen onLogin={(email) => { localStorage.setItem('sp_session', email); setSession(email); setRoute({ v: 'home' }); }} /></Frame>;
  const D = RallyData.scope(scopeId);
  const questList = scopeId === 'brand'
    ? [...quests.flagship.map(q => ({ ...q, o: 'GW' })), ...quests.kiosk.map(q => ({ ...q, o: 'RP' }))]
    : quests[scopeId];
  const custList = custs.filter(c => scopeId === 'brand' || c.outlet === scopeId);
  const onLaunch = (outlet, q) => setQuests(qs => ({ ...qs, [outlet]: [{ id: qs[outlet].length + 1, ...q }, ...qs[outlet]] }));
  const sendMsg = (id, text) => {
    setCusts(cs => cs.map(c => c.id === id ? { ...c, msgs: [...c.msgs, { f: 'm', t: text, time: 'now' }] } : c));
    const c = custs.find(x => x.id === id);
    if (c && c.reply && !c.replied) setTimeout(() => setCusts(cs => cs.map(x => x.id === id ? { ...x, replied: true, msgs: [...x.msgs, { f: 'c', t: x.reply, time: 'now' }] } : x)), 1800);
  };
  const v = route.v;
  const body = v === 'quests' ? <QuestsScreen D={D} scopeId={scopeId} quests={questList} nav={nav} />
    : v === 'library' ? <LibraryScreen nav={nav} />
    : v === 'questNew' ? <QuestNewScreen scopeId={scopeId} preSeg={route.a && route.a.seg} onLaunch={onLaunch} nav={nav} />
    : v === 'segments' ? <SegmentsScreen D={D} nav={nav} />
    : v === 'segment' ? <SegmentDetailScreen D={D} id={route.a} nav={nav} />
    : v === 'compare' ? <CompareScreen nav={nav} />
    : v === 'journey' ? <JourneyScreen D={D} openStage={typeof route.a === 'number' ? route.a : undefined} segId={route.a && route.a.seg} />
    : v === 'chat' ? <ChatScreen scopeId={scopeId} D={D} initialAsk={route.a && route.a.ask} />
    : v === 'messages' ? <MessagesScreen custs={custList} scopeId={scopeId} nav={nav} />
    : v === 'thread' ? <ThreadScreen custs={custs} id={route.a} onSend={sendMsg} nav={nav} />
    : v === 'account' ? <AccountScreen email={session} onSignOut={() => { localStorage.removeItem('sp_session'); setSession(null); }} userMode={userMode} setUserMode={(v2) => setTweak('userMode', v2)} avatarStyle={tw.avatarStyle} setAvatarStyle={(v2) => setTweak('avatarStyle', v2)} />
    : <HomeScreen D={D} scopeId={scopeId} nav={nav} quests={questList} custs={custList} userMode={userMode} setScope={setScope} />;
  const tab = v === 'segment' || v === 'compare' ? 'segments' : v === 'questNew' || v === 'library' ? 'quests' : v === 'thread' ? 'messages' : v === 'journey' || v === 'account' ? 'home' : v;
  return <Frame>
    <StatusRow nav={nav} onBell={() => { setNotifs(o => !o); setSeen(true); }} unread={seen ? 0 : (NOTIFS[scopeId] || []).length} />
    <Switcher scopeId={scopeId} setScope={setScope} open={switcherOpen} setOpen={setSwitcherOpen} nav={nav} />
    <div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>{body}</div>
    <nav style={{ display: 'flex', borderTop: '1px solid var(--ink)', background: 'var(--paper)', flexShrink: 0 }}>
      {NAV.map(([id, icon, label]) => {
        const active = tab === id;
        return <button key={id} onClick={() => nav(id)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, padding: '10px 0 12px', background: active ? 'var(--ink)' : 'transparent', color: active ? 'var(--white)' : 'var(--ink)', border: 'none', cursor: 'pointer', transition: 'background 120ms var(--ease-snap)' }}>
          {icon === 'face' ? <span className={id === 'chat' && explain ? 'rally-talk' : ''} style={{ display: 'inline-flex' }}><XFace size={24} talking={!!explain} /></span> : <XIcon name={icon} size={24} />}
          <span className="u-pixel" style={{ fontSize: 10 }}>{label}</span>
        </button>;
      })}
    </nav>
    {notifs && <NotifSheet scopeId={scopeId} onClose={() => setNotifs(false)} nav={nav} />}
    {explain && <XSpeech pointer="bottom" pointerOffset={28} tag="RALLY" onClose={() => setExplain(null)} style={{ position: 'absolute', right: 10, bottom: 74, width: 280, zIndex: 20, boxShadow: '4px 4px 0 var(--ink)' }}>
      <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.4, textWrap: 'pretty' }}>{explain}</div>
    </XSpeech>}
    <TweaksPanel>
      <TweakSection label="User mode" />
      <TweakRadio label="Signed in as" value={userMode} options={['owner', 'manager']} onChange={(v) => setTweak('userMode', v)} />
      <TweakSection label="Segments" />
      <TweakRadio label="Avatars" value={tw.avatarStyle} options={['mascot', 'photo']} onChange={(v) => setTweak('avatarStyle', v)} />
    </TweaksPanel>
  </Frame>;
}

function Frame({ children }) {
  return <div className="app-frame" style={{ position: 'relative', background: 'var(--paper)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>{children}</div>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
