/* MSN Messenger (circa 2001) */

const { useState, useEffect, useRef } = React;

const MSN_STATUSES = [
  { id: 'online',    label: 'En ligne',         color: '#3aa53a', dot: '🟢' },
  { id: 'busy',      label: 'Occupé',           color: '#d83a3a', dot: '🔴' },
  { id: 'away',      label: 'Absent',           color: '#e4a500', dot: '🟡' },
  { id: 'brb',       label: 'De retour bientôt', color: '#e4a500', dot: '🟡' },
  { id: 'phone',     label: 'Au téléphone',     color: '#e4a500', dot: '🟡' },
  { id: 'lunch',     label: 'À la pause déjeuner', color: '#e4a500', dot: '🟡' },
  { id: 'invisible', label: 'Apparaître hors ligne', color: '#888', dot: '⚪' },
];

const MSN_CONTACTS = [
  { id: 'sophie',  name: 'Sophie ✿ ~xXx~',    avatar: '👱‍♀️', status: 'online', psm: 'écoute Britney en boucle 🎶', auto: ['salut ça va ?', 'tu fais quoi ce soir ?', 'lol', 'A/S/V ? mdr je rigole 😄'] },
  { id: 'kevin',   name: '★ KeVin ★ [tHe BeSt]', avatar: '🧑', status: 'busy', psm: 'révise le bac... pfff', auto: ['cc', 'pas le temps là je révise 😭', 'tu sais quoi pr les maths ?', 'thx bcp'] },
  { id: 'manon',   name: 'manOOn  ♥',          avatar: '👩', status: 'online', psm: '♥ Tom ♥ 4 ever', auto: ['hihi', 'tu as vu le nouveau clip ?', 'jtdr ♥', 'g un nouveau msn dis le pas'] },
  { id: 'thomas',  name: 'ToM [absent ne pas déranger]', avatar: '🧔', status: 'away', psm: 'devant la PS2', auto: [] },
  { id: 'mum',     name: 'Maman',              avatar: '👩‍🦰', status: 'online', psm: '', auto: ['Tu as fait tes devoirs ?', "N'oublie pas de débrancher avant l'orage", 'Le repas est prêt !', "Tu as remercié ta tante ?"] },
  { id: 'julien',  name: 'JuLi3n_75',          avatar: '🧑‍🎤', status: 'phone', psm: 'au tél avec ma copine', auto: ['re', 'attends 2s', 'voilà me revoilà'] },
  { id: 'aurelie', name: 'Aurélie',            avatar: '👩‍🎓', status: 'offline', psm: '', auto: [] },
  { id: 'maxime',  name: 'maxxx_skater',       avatar: '🛹', status: 'offline', psm: '', auto: [] },
  { id: 'lea',     name: 'Léa',                avatar: '👧', status: 'offline', psm: '', auto: [] },
];

const EMOTICONS = [
  { code: ':)',  glyph: '🙂' },
  { code: ':D',  glyph: '😄' },
  { code: ':P',  glyph: '😋' },
  { code: ':(',  glyph: '🙁' },
  { code: ":'(", glyph: '😢' },
  { code: ';)',  glyph: '😉' },
  { code: ':@',  glyph: '😡' },
  { code: '(L)', glyph: '❤️' },
  { code: '(F)', glyph: '🌹' },
  { code: '(K)', glyph: '💋' },
  { code: '(Y)', glyph: '👍' },
  { code: '(N)', glyph: '👎' },
  { code: '(*)', glyph: '⭐' },
  { code: '(8)', glyph: '🎵' },
  { code: '(S)', glyph: '🌙' },
  { code: '(C)', glyph: '☕' },
];

function statusInfo(id) { return MSN_STATUSES.find(s => s.id === id) || MSN_STATUSES[6]; }

/* ============== Buddy List ============== */
function MsnMessenger({ open }) {
  const [myStatus, setMyStatus] = useState('online');
  const [myName] = useState('Moi - le pingouin');
  const [psm, setPsm] = useState('« Le futur appartient à ceux qui se lèvent tôt »');
  const [statusOpen, setStatusOpen] = useState(false);

  const groups = {
    'En ligne (5)':  MSN_CONTACTS.filter(c => ['online','busy','away','phone','lunch','brb'].includes(c.status)),
    'Hors ligne (3)': MSN_CONTACTS.filter(c => c.status === 'offline'),
  };

  const openChat = (contact) => {
    open && open('msn-chat', { payload: contact, allowMultiple: true, titleSuffix: contact.name });
  };

  return (
    <div className="msn-shell">
      <div className="msn-banner">
        <div className="msn-banner-bird">
          <svg width="22" height="22" viewBox="0 0 22 22">
            <ellipse cx="11" cy="13" rx="8" ry="7" fill="#fff"/>
            <ellipse cx="11" cy="11" rx="9" ry="6" fill="#3a9d3a"/>
            <circle cx="14" cy="9" r="1.6" fill="#fff"/>
            <circle cx="14.3" cy="9" r="0.7" fill="#000"/>
            <path d="M17 11 L20 12 L17 13 Z" fill="#ffa000"/>
          </svg>
        </div>
        <div style={{ flex: 1 }}>
          <div className="msn-banner-title">.NET Messenger Service</div>
          <div className="msn-banner-tag">Une nouvelle façon de discuter</div>
        </div>
      </div>

      <div className="msn-me">
        <div className="msn-avatar">
          <div className="msn-avatar-img">🐧</div>
          <div className="msn-status-dot" style={{ background: statusInfo(myStatus).color }}></div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="msn-me-name">
            <span style={{ fontWeight: 'bold' }}>{myName}</span>
            <span className="msn-me-status" onClick={() => setStatusOpen(v => !v)}>
              ({statusInfo(myStatus).label}) ▾
            </span>
            {statusOpen && (
              <>
                <div style={{ position: 'fixed', inset: 0, zIndex: 50 }} onClick={() => setStatusOpen(false)}></div>
                <div className="msn-status-menu">
                  {MSN_STATUSES.map(s => (
                    <div
                      key={s.id}
                      className="msn-status-menu-item"
                      onClick={() => { setMyStatus(s.id); setStatusOpen(false); }}
                    >
                      <span style={{ color: s.color }}>●</span> {s.label}
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
          <input
            className="msn-psm"
            value={psm}
            onChange={(e) => setPsm(e.target.value)}
            placeholder="Tapez un message personnel..."
          />
        </div>
      </div>

      <div className="msn-toolbar">
        <button className="msn-tool">👤 Ajouter</button>
        <button className="msn-tool">✉ Envoyer</button>
        <button className="msn-tool">📞 Appeler</button>
        <button className="msn-tool">📁 Partager</button>
      </div>

      <div className="msn-list">
        {Object.entries(groups).map(([label, list]) => (
          <MsnGroup key={label} label={label} contacts={list} onChat={openChat} />
        ))}
      </div>

      <div className="msn-footer">
        <span>Cliquez ici pour découvrir Hotmail !</span>
      </div>
    </div>
  );
}

function MsnGroup({ label, contacts, onChat }) {
  const [open, setOpen] = useState(true);
  return (
    <div className="msn-group">
      <div className="msn-group-header" onClick={() => setOpen(o => !o)}>
        <span className="msn-group-arrow">{open ? '▼' : '▶'}</span>
        <span>{label}</span>
      </div>
      {open && contacts.map(c => {
        const offline = c.status === 'offline';
        return (
          <div
            key={c.id}
            className={`msn-contact ${offline ? 'offline' : ''}`}
            onDoubleClick={() => !offline && onChat(c)}
            title={offline ? "Ce contact est hors ligne" : "Double-cliquez pour discuter"}
          >
            <div className="msn-contact-icon">
              <span className="msn-contact-emoji">{c.avatar}</span>
              <span className="msn-contact-dot" style={{ background: offline ? '#999' : statusInfo(c.status).color }}></span>
            </div>
            <div className="msn-contact-name">
              <span className="msn-contact-display">{c.name}</span>
              {c.psm && <span className="msn-contact-psm"> - {c.psm}</span>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ============== Chat window ============== */
function MsnChat({ payload }) {
  const contact = payload || MSN_CONTACTS[0];
  const [msgs, setMsgs] = useState([
    { from: 'system', text: `Vous discutez maintenant avec ${contact.name}` },
  ]);
  const [draft, setDraft] = useState('');
  const [theyTyping, setTheyTyping] = useState(false);
  const [showEmos, setShowEmos] = useState(false);
  const [font, setFont] = useState({ family: 'Comic Sans MS', color: '#7a1fa0', bold: false, italic: false });
  const [nudged, setNudged] = useState(false);
  const scrollRef = useRef(null);
  const replyTimer = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, theyTyping]);

  const replaceEmos = (txt) => {
    let out = txt;
    EMOTICONS.forEach(e => { out = out.split(e.code).join(e.glyph); });
    return out;
  };

  const send = () => {
    const t = draft.trim();
    if (!t) return;
    setMsgs(m => [...m, { from: 'me', text: replaceEmos(t), font }]);
    setDraft('');
    // auto reply if contact has one
    if (contact.auto && contact.auto.length) {
      clearTimeout(replyTimer.current);
      setTimeout(() => setTheyTyping(true), 600);
      replyTimer.current = setTimeout(() => {
        setTheyTyping(false);
        const reply = contact.auto[Math.floor(Math.random() * contact.auto.length)];
        setMsgs(m => [...m, { from: 'them', text: replaceEmos(reply) }]);
        if (window.Sounds) window.Sounds.msgIn();
      }, 1400 + Math.random() * 1200);
    }
  };

  const sendNudge = () => {
    setMsgs(m => [...m, { from: 'system', text: `Vous venez d'envoyer un wizz à ${contact.name.split(' ')[0]}` }]);
    setNudged(true);
    if (window.Sounds) window.Sounds.nudge();
    setTimeout(() => setNudged(false), 700);
  };

  return (
    <div className={`msn-chat-shell ${nudged ? 'nudge' : ''}`}>
      <div className="msn-chat-header">
        <div className="msn-chat-them">
          <div className="msn-avatar" style={{ width: 32, height: 32 }}>
            <div className="msn-avatar-img" style={{ fontSize: 22 }}>{contact.avatar}</div>
            <div className="msn-status-dot" style={{ background: statusInfo(contact.status).color }}></div>
          </div>
          <div>
            <div style={{ fontWeight: 'bold' }}>{contact.name.replace(/\s+/g, ' ')}</div>
            <div style={{ fontSize: 10, color: '#555' }}>&lt;contact@hotmail.com&gt;</div>
          </div>
        </div>
        <div className="msn-avatar" style={{ width: 38, height: 38 }}>
          <div className="msn-avatar-img" style={{ fontSize: 26 }}>🐧</div>
        </div>
      </div>

      <div className="msn-chat-toolbar">
        <button className="msn-tool small">📩 Inviter</button>
        <button className="msn-tool small">📁 Fichier</button>
        <button className="msn-tool small">🎥 Vidéo</button>
        <button className="msn-tool small">🎮 Activités</button>
        <button className="msn-tool small">💻 Demander de l'aide</button>
      </div>

      <div className="msn-messages" ref={scrollRef}>
        {msgs.map((m, i) => {
          if (m.from === 'system') {
            return <div key={i} className="msn-msg-sys">{m.text}</div>;
          }
          const f = m.font || (m.from === 'me' ? font : { family: 'Tahoma', color: '#1a47b8', bold: false, italic: false });
          return (
            <div key={i} className="msn-msg">
              <div className="msn-msg-author" style={{ color: m.from === 'me' ? '#b51717' : '#1a47b8' }}>
                {m.from === 'me' ? 'Moi - le pingouin dit :' : `${contact.name.split(' ')[0]} dit :`}
              </div>
              <div className="msn-msg-body" style={{
                fontFamily: `"${f.family}", sans-serif`,
                color: f.color,
                fontWeight: f.bold ? 'bold' : 'normal',
                fontStyle: f.italic ? 'italic' : 'normal',
              }}>{m.text}</div>
            </div>
          );
        })}
        {theyTyping && (
          <div className="msn-typing">
            <span className="msn-typing-dots"><span></span><span></span><span></span></span>
            <span>{contact.name.split(' ')[0]} est en train d'écrire un message...</span>
          </div>
        )}
      </div>

      <div className="msn-font-bar">
        <button
          className={`msn-fbtn ${font.bold ? 'on' : ''}`}
          onClick={() => setFont(f => ({...f, bold: !f.bold}))}
          style={{ fontWeight: 'bold' }}
        >B</button>
        <button
          className={`msn-fbtn ${font.italic ? 'on' : ''}`}
          onClick={() => setFont(f => ({...f, italic: !f.italic}))}
          style={{ fontStyle: 'italic' }}
        >I</button>
        <select
          value={font.family}
          onChange={(e) => setFont(f => ({...f, family: e.target.value}))}
          className="msn-font-select"
        >
          <option>Comic Sans MS</option>
          <option>Tahoma</option>
          <option>Arial</option>
          <option>Courier New</option>
          <option>Times New Roman</option>
        </select>
        {['#7a1fa0','#b51717','#0066cc','#3aa53a','#e07a00','#000000'].map(c => (
          <button
            key={c}
            className={`msn-color ${font.color === c ? 'on' : ''}`}
            style={{ background: c }}
            onClick={() => setFont(f => ({...f, color: c}))}
          />
        ))}
        <div style={{ flex: 1 }}></div>
        <button
          className="msn-fbtn"
          onClick={() => setShowEmos(v => !v)}
          title="Émoticônes"
        >☺</button>
        <button
          className="msn-fbtn"
          onClick={sendNudge}
          title="Envoyer un wizz"
          style={{ fontSize: 13 }}
        >⚡</button>
      </div>

      {showEmos && (
        <div className="msn-emo-popup">
          {EMOTICONS.map(e => (
            <button
              key={e.code}
              className="msn-emo-btn"
              onClick={() => { setDraft(d => d + e.code); setShowEmos(false); }}
              title={e.code}
            >{e.glyph}</button>
          ))}
        </div>
      )}

      <div className="msn-input-area">
        <textarea
          className="msn-input"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
          }}
          placeholder={`Tapez votre message à ${contact.name.split(' ')[0]}...`}
          style={{
            fontFamily: `"${font.family}", sans-serif`,
            color: font.color,
            fontWeight: font.bold ? 'bold' : 'normal',
            fontStyle: font.italic ? 'italic' : 'normal',
          }}
        />
        <button className="msn-send" onClick={send}>Envoyer</button>
      </div>
    </div>
  );
}

window.MsnMessenger = MsnMessenger;
window.MsnChat = MsnChat;
