// Chat — both as floating drawer (FAB → slide-in) and as inline embed (final CTA).
// Mocked dialogue: pre-scripted scenarios selected by user's first message or hint.

function classifyScenario(text, dict) {
  const l = text.toLowerCase();
  if (l.includes('wildberries') || l.includes('магазин') || l.includes('marketplace') || l.includes('shop')) return 'wildberries';
  if (l.includes('клон') || l.includes('рутин') || l.includes('clone') || l.includes('routine')) return 'assistant';
  if (l.includes('менеджер') || l.includes('заменить') || l.includes('manager') || l.includes('cut to') || l.includes('replace')) return 'manager';
  return null;
}

function MessageBody({ text }) {
  // very tiny markdown: **bold**, single newlines
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return (
    <>{parts.map((p, i) => {
      if (p.startsWith('**') && p.endsWith('**')) return <strong key={i}>{p.slice(2, -2)}</strong>;
      return <React.Fragment key={i}>{p}</React.Fragment>;
    })}</>
  );
}

function ChatBody({ t, lang, prefill, scenarioHint, onEscalate }) {
  const dict = t.chat;
  const [messages, setMessages] = React.useState(dict.scenarios.default);
  const [typing, setTyping] = React.useState(false);
  const [quickReplies, setQuickReplies] = React.useState(dict.quickreplies_default);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);
  const [usedPrefill, setUsedPrefill] = React.useState(null);
  const inputRef = React.useRef(null);

  // Apply prefill or scenarioHint once
  React.useEffect(() => {
    if (prefill && prefill !== usedPrefill) {
      setUsedPrefill(prefill);
      sendUserMessage(prefill);
    }
  }, [prefill]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, typing]);

  // Reset on language change
  React.useEffect(() => {
    setMessages(dict.scenarios.default);
    setQuickReplies(dict.quickreplies_default);
  }, [lang]);

  function playScenario(key) {
    const script = dict.scenarios[key];
    if (!script) return;
    // The first message is the user echo we already pushed; play the rest with typing pauses.
    let acc = [];
    setMessages((msgs) => msgs);
    let i = 1;
    const advance = () => {
      if (i >= script.length) {
        setTyping(false);
        setQuickReplies(dict.quickreplies_after);
        return;
      }
      const m = script[i];
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMessages((prev) => [...prev, m]);
        i++;
        // small pause then next
        setTimeout(advance, 360);
      }, 1100 + Math.random() * 600);
    };
    setTimeout(advance, 460);
  }

  function sendUserMessage(text) {
    if (!text || !text.trim()) return;
    const userMsg = { role: 'user', text: text.trim() };
    setMessages((prev) => [...prev, userMsg]);
    setInput('');
    // pick scenario
    const key = classifyScenario(text, dict);
    if (key) {
      playScenario(key);
    } else {
      // generic bot reply
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMessages((prev) => [...prev, {
          role: 'bot',
          text: lang === 'ru'
            ? 'Понял. Чтобы дать вилку и срок — расскажите чуть подробнее:\n\n— Где сейчас живёт боль (канал, инструмент)?\n— Каков объём в день / месяц?\n— Что хотите получить через 30 дней?'
            : 'Got it. To give a real ballpark — tell me a bit more:\n\n— Where does the pain live today (channel, tool)?\n— What is the daily / monthly volume?\n— What do you want in 30 days?'
        }]);
        setQuickReplies(dict.quickreplies_after);
      }, 1300);
    }
  }

  function applyHint(num) {
    // Map chapter number to a quick scenario fragment
    const hints = lang === 'ru' ? {
      '01': 'Хочу AI-сотрудника для отдела продаж',
      '02': 'Хочу автоматизировать рутину для команды из 12 человек',
      '03': 'Нужно on-premise решение, у нас регулируемая отрасль',
      '04': 'Хочу умный Telegram-бот с памятью и голосом',
      '05': 'Хочу Telegram Mini App вместо мобильного приложения',
    } : {
      '01': 'I want an AI employee for sales',
      '02': 'I want to automate routine for a 12-person team',
      '03': 'We need on-prem, regulated industry',
      '04': 'I want a smart Telegram bot with memory and voice',
      '05': 'I want a Telegram Mini App instead of mobile app',
    };
    if (hints[num]) sendUserMessage(hints[num]);
  }

  // Expose hint application via prefill
  React.useEffect(() => {
    if (scenarioHint && /^0\d$/.test(scenarioHint)) applyHint(scenarioHint);
  }, [scenarioHint]);

  return (
    <div className="chat-embed">
      <div className="chat-head">
        <div className="chat-avatar">A</div>
        <div className="chat-head-meta">
          <div className="name">{dict.name} <span style={{ color: 'var(--muted)', fontWeight: 400, fontSize: 12, marginLeft: 6 }}>{dict.role}</span></div>
          <div className="status"><span className="dot"/> {dict.status}</div>
        </div>
        <button onClick={onEscalate} style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.06em', color: 'var(--fg-dim)', border: '1px solid var(--line-strong)', borderRadius: 999, padding: '6px 10px' }}>
          {dict.escalate}
        </button>
      </div>
      <div className="chat-messages" ref={scrollRef}>
        {messages.map((m, i) => (
          <div key={i} className={'msg ' + m.role}>
            <MessageBody text={m.text} />
          </div>
        ))}
        {typing && <div className="typing"><span/><span/><span/></div>}
      </div>
      <div className="chat-quickreplies">
        {quickReplies.map((q) => (
          <button key={q} className="qr" onClick={() => sendUserMessage(q)}>{q}</button>
        ))}
      </div>
      <form className="chat-input" onSubmit={(e) => { e.preventDefault(); sendUserMessage(input); }}>
        <input
          ref={inputRef}
          placeholder={dict.placeholder}
          value={input}
          onChange={(e) => setInput(e.target.value)}
        />
        <button type="submit" aria-label="send">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 7 L12 7 M7 2 L12 7 L7 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </form>
    </div>
  );
}

function FloatingChat({ t, lang, isOpen, setOpen, chatProps }) {
  return (
    <>
      <button className={'fab gradient'} onClick={() => setOpen(true)} aria-label="Open chat" style={{ display: isOpen ? 'none' : 'inline-flex' }}>
        <span className="pulse"/>
        <span>{t.chat.name} · {t.cta_open_chat}</span>
      </button>
      <div className={'chat-drawer ' + (isOpen ? 'open' : '')}>
        <button className="chat-close" onClick={() => setOpen(false)} aria-label="Close chat">×</button>
        <ChatBody t={t} lang={lang} {...chatProps} onEscalate={() => alert(lang === 'ru' ? 'Менеджер свяжется с вами в TG в течение 15 минут.' : 'A human will ping you on Telegram within 15 minutes.')} />
      </div>
    </>
  );
}

window.Chat = { ChatBody, FloatingChat };
