// ============ Yap — app shell, routing, state, tweaks ============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#5A57F2",
  "bubbleRadius": 22,
  "cardRadius": 24,
  "bubbleTail": true
}/*EDITMODE-END*/;

// peer auto-replies (light, playful)
const REPLIES = [
  'haha oui carrément', 'ok je note 👌', 'mdrr', 'attends je regarde',
  'trop bien ça', 'je te dis ça vite 🙏', 'oui ! 🔥', 'ahhh d\'accord je vois',
  'genial', 'on en parle demain ?', '🥹🥹', 'je suis 100% d\'accord',
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [screen, setScreen] = useState('onboarding'); // onboarding | app
  const [tab, setTab] = useState('chats');
  const [activeId, setActiveId] = useState(null);
  const [query, setQuery] = useState('');
  const [typing, setTyping] = useState(false);
  const replyTimers = useRef([]);

  // messages keyed by conversation id
  const [allMessages, setAllMessages] = useState(() => {
    const m = {};
    CONVERSATIONS.forEach(c => { m[c.id] = c.messages.map(x => ({ ...x })); });
    return m;
  });

  const activeConv = CONVERSATIONS.find(c => c.id === activeId);

  function openChat(id) { setActiveId(id); }
  function closeChat() { setActiveId(null); setTyping(false);
    replyTimers.current.forEach(clearTimeout); replyTimers.current = []; }

  function sendMessage(text) {
    const conv = activeConv;
    if (!conv) return;
    const now = new Date();
    const time = now.getHours() + ':' + String(now.getMinutes()).padStart(2, '0');
    const mine = { id: 'u' + Date.now(), from: 'me', text, time };
    setAllMessages(prev => ({ ...prev, [conv.id]: [...(prev[conv.id] || []), mine] }));

    // auto reply
    const responder = conv.group ? conv.group.members[Math.floor(Math.random() * conv.group.members.length)] : conv.peer;
    const t1 = setTimeout(() => setTyping(true), 700);
    const t2 = setTimeout(() => {
      setTyping(false);
      const reply = REPLIES[Math.floor(Math.random() * REPLIES.length)];
      const r = { id: 'r' + Date.now(), from: responder, text: reply, time };
      setAllMessages(prev => ({ ...prev, [conv.id]: [...(prev[conv.id] || []), r] }));
    }, 700 + 1300 + Math.random() * 600);
    replyTimers.current.push(t1, t2);
  }

  useEffect(() => () => replyTimers.current.forEach(clearTimeout), []);

  const unreadChats = CONVERSATIONS.reduce((n, c) => n + (c.unread > 0 ? 1 : 0), 0);
  const unreadNotifs = NOTIFS.filter(n => n.unread).length;

  // ----- accent + radius applied as CSS vars on the app root -----
  const rootStyle = {
    '--brand': t.accent,
    '--brand-deep': `color-mix(in oklab, ${t.accent}, #000 18%)`,
    '--brand-soft': `color-mix(in oklab, ${t.accent}, #fff 86%)`,
    '--bubble-radius': t.bubbleRadius + 'px',
    '--card-radius': t.cardRadius + 'px',
  };

  let body;
  if (screen === 'onboarding') {
    body = <OnboardingScreen onEnter={() => { setScreen('app'); setTab('chats'); }} />;
  } else if (tab === 'chats' && activeConv) {
    body = <ChatDetailScreen conv={activeConv} messages={allMessages[activeConv.id] || []}
      onBack={closeChat} onSend={sendMessage} typing={typing} />;
  } else {
    const screens = {
      chats: <ChatListScreen allMessages={allMessages} onOpen={openChat} query={query} setQuery={setQuery} />,
      feed: <FeedScreen />,
      notifs: <NotifsScreen />,
      profile: <ProfileScreen />,
    };
    body = (
      <React.Fragment>
        {screens[tab]}
        <BottomNav tab={tab} onTab={(id) => { setTab(id); setActiveId(null); }}
          unreadChats={unreadChats} unreadNotifs={unreadNotifs} />
      </React.Fragment>
    );
  }

  return (
    <div className={'app' + (t.bubbleTail ? '' : ' bubbles--notail')} style={rootStyle}>
      {body}

      <TweaksPanel>
        <TweakSection label="Forme" />
        <TweakSlider label="Arrondi des bulles" value={t.bubbleRadius} min={6} max={26} step={1} unit="px"
          onChange={v => setTweak('bubbleRadius', v)} />
        <TweakSlider label="Arrondi des cartes" value={t.cardRadius} min={6} max={32} step={1} unit="px"
          onChange={v => setTweak('cardRadius', v)} />
        <TweakToggle label="Queue des bulles" value={t.bubbleTail}
          onChange={v => setTweak('bubbleTail', v)} />
        <TweakSection label="Couleur" />
        <TweakColor label="Accent" value={t.accent}
          options={['#5A57F2', '#7C3AED', '#2E7DF6', '#0EA5A0', '#F2674E']}
          onChange={v => setTweak('accent', v)} />
      </TweaksPanel>
    </div>
  );
}

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