/* global React */
// AtelierChat — bilingual (EN/AR) Nazarban consultation chat.
// Talks to /api/chat and /api/collect-email; falls back to a local reply offline.

const NZ_MARK = (
  <svg viewBox="-4 -4 506.9 400.31" fill="none" aria-hidden="true">
    <path d="M299.7 299.66L163.97 104.37L163.97 275.06C163.97 288.9 169.31 296.6 179.97 298.18L179.97 299.66L145.3 299.66L145.3 298.18C155.97 296.8 161.3 289.1 161.3 275.06L161.3 116.82C161.3 102.79 155.97 95.09 145.3 93.7L145.3 92.22L180.57 92.22L299.7 265.88L302.37 269.73L322.81 299.66Z" fill="currentColor"/>
    <path d="M330.48 299.66L197.19 107.88C194.15 103.51 190.28 99.72 185.66 97.08C182.9 95.5 179.64 94.16 176.08 93.7L176.08 92.22L211.35 92.22L333.14 269.73L353.59 299.66Z" fill="currentColor"/>
    <path d="M164.13 114.39L164.13 124.56L285.55 300.08L292.33 300.08Z" fill="currentColor"/>
    <path d="M327.29 116.82L327.29 264.36L329.96 264.36L329.96 116.82C329.96 102.79 335.29 95.08 345.96 93.7L345.96 92.22L311.29 92.22L311.29 93.7C321.96 95.28 327.29 102.99 327.29 116.82" fill="currentColor"/>
  </svg>
);

const I = {
  flow:  <svg viewBox="0 0 24 24" fill="none"><circle cx="6" cy="6" r="2.3" stroke="currentColor" strokeWidth="1.5"/><circle cx="18" cy="6" r="2.3" stroke="currentColor" strokeWidth="1.5"/><circle cx="12" cy="18" r="2.3" stroke="currentColor" strokeWidth="1.5"/><path d="M8 7.6l3 8M16 7.6l-3 8" stroke="currentColor" strokeWidth="1.5"/></svg>,
  bot:   <svg viewBox="0 0 24 24" fill="none"><rect x="4.5" y="8.5" width="15" height="10.5" rx="2.5" stroke="currentColor" strokeWidth="1.5"/><path d="M12 4.5v4M9.3 13.2h.01M14.7 13.2h.01" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/></svg>,
  doc:   <svg viewBox="0 0 24 24" fill="none"><path d="M7 3.5h7l4 4v13H7z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/><path d="M14 3.5v4h4M10 13h5M10 16h5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  chart: <svg viewBox="0 0 24 24" fill="none"><path d="M4 19.5V5M4 19.5h16M8 16v-3.5M12 16V8.5M16 16v-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  send:  <svg viewBox="0 0 24 24" fill="none"><path d="M4 11.5l15.5-7-7 15.5-2-6.2-6.5-2.3z" fill="currentColor"/></svg>,
  arrow: <svg viewBox="0 0 24 24" fill="none"><path d="M5 12h13M12.5 5.5L19 12l-6.5 6.5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  doc2:  <svg viewBox="0 0 24 24" fill="none"><path d="M7 3.5h7l4 4v13H7z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M14 3.5v4h4M10 13h5M10 16.5h5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  x:     <svg viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>,
  check: <svg viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  mail:  <svg viewBox="0 0 24 24" fill="none"><rect x="3" y="5.5" width="18" height="13" rx="2" stroke="currentColor" strokeWidth="1.6"/><path d="M4 7.5l8 5.5 8-5.5" stroke="currentColor" strokeWidth="1.6"/></svg>,
  phone: <svg viewBox="0 0 24 24" fill="none"><path d="M6 3.5h3l1.4 4.6-1.9 1.4a12 12 0 005.6 5.6l1.4-1.9 4.6 1.4v3a1.8 1.8 0 01-1.9 1.8A16 16 0 014.2 5.4 1.8 1.8 0 016 3.5z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>,
};

const PROMPT_ICONS = [I.flow, I.bot, I.doc, I.chart];

// --- bilingual strings ---
const T = {
  en: {
    consultant: 'AI Consultant', online: 'Online', getProposal: 'Get a proposal',
    welcomeEyebrow: 'Consultation',
    welcomeH2: <>Let us scope your <em>intelligent</em> solution.</>,
    welcomeP: "Describe a process, a constraint, or an ambition. We translate it into a secure, working system — quietly, and well.",
    prompts: ['Automate a manual workflow', 'Build a custom AI assistant', 'Process documents at scale', 'Forecast demand from our data'],
    inputPh: "Describe a process you'd like to automate…",
    propH3: 'Get your free AI proposal',
    propSub: "We'll review what you've described and send a tailored, no-obligation proposal—scope, timeline, and a path to a 14-day pilot—within 24 hours.",
    emailPh: 'your@email.com', send: 'Send it', sending: 'Sending…',
    sendError: "Something went wrong and your request didn't go through — please try again.",
    propFine: 'A summary of this chat is included',
    noChatH3: 'Chat with us first',
    noChatSub: 'Tell us about your project so we can tailor your proposal — even a sentence helps.',
    startChatting: 'Start chatting',
    sentH3: 'Proposal on its way.',
    sentSub: (e) => <>Thank you—we'll be in touch at <strong>{e}</strong> within 24 hours with a tailored proposal. You can keep the conversation going in the meantime.</>,
    backToChat: 'Back to chat',
    farewell: "Thank you — we'll be in touch shortly with next steps.",
    fallback: "Noted. The fastest way to know if this is worth it is a scoped proof-of-concept against your own data. Tell me the process, the volume, and what 'good' looks like — and I'll map the path to a working pilot.",
  },
  ar: {
    consultant: 'مستشار الذكاء الاصطناعي', online: 'متصل', getProposal: 'اطلب عرضًا',
    welcomeEyebrow: 'استشارة',
    welcomeH2: <>لنرسم ملامح <em>الحل الذكي</em> المناسب لك.</>,
    welcomeP: 'صِف لنا عمليةً أو قيدًا أو طموحًا، ونحوّله إلى نظامٍ آمنٍ يعمل فعليًا — بهدوءٍ وإتقان.',
    prompts: ['أتمتة سير عمل يدوي', 'بناء مساعد ذكاء اصطناعي مخصّص', 'معالجة المستندات على نطاق واسع', 'التنبّؤ بالطلب من بياناتك'],
    inputPh: 'صِف عمليةً ترغب في أتمتتها…',
    propH3: 'احصل على عرض الذكاء الاصطناعي المجاني',
    propSub: 'سنراجع ما وصفته ونرسل إليك عرضًا مخصّصًا دون أي التزام — النطاق والجدول الزمني ومسار إطلاق تجريبي خلال 14 يومًا — في غضون 24 ساعة.',
    emailPh: 'بريدك الإلكتروني', send: 'أرسله', sending: 'جارٍ الإرسال…',
    sendError: 'حدث خطأ ولم يتم إرسال طلبك — يرجى المحاولة مرة أخرى.',
    propFine: 'سيُرفَق ملخّص هذه المحادثة',
    noChatH3: 'تحدّث معنا أولًا',
    noChatSub: 'أخبرنا عن مشروعك حتى نتمكن من تخصيص عرضك — حتى جملة واحدة تكفي.',
    startChatting: 'ابدأ المحادثة',
    sentH3: 'العرض في طريقه إليك.',
    sentSub: (e) => <>شكرًا لك — سنتواصل معك على <strong>{e}</strong> خلال 24 ساعة بعرضٍ مخصّص. يمكنك متابعة المحادثة في هذه الأثناء.</>,
    backToChat: 'العودة إلى المحادثة',
    farewell: 'شكرًا لك — سنتواصل معك قريبًا بالخطوات التالية.',
    fallback: 'تمام. أسرع طريقة لمعرفة الجدوى هي إثباتٌ عمليٌّ محدّد على بياناتك. صِف لنا العملية والحجم وما يعنيه «النجاح» بالنسبة لك، وسنرسم مسار الوصول إلى نموذج تجريبي يعمل.',
  },
};

function useLang() {
  const [lang, setLang] = React.useState(window.NZ_LANG ? window.NZ_LANG.get() : 'en');
  React.useEffect(() => {
    const h = (e) => setLang(e.detail.lang);
    document.addEventListener('languagechange', h);
    return () => document.removeEventListener('languagechange', h);
  }, []);
  return lang;
}

function ProposalPopup({ onClose, getConversation, hasConversation }) {
  const lang = useLang();
  const t = T[lang];
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [failed, setFailed] = React.useState(false);
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || busy) return;
    setBusy(true);
    setFailed(false);
    try {
      const res = await fetch('/api/collect-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(), source: 'popup',
          conversationHistory: (getConversation && getConversation()) || [],
          language: lang,
        }),
      });
      if (!res.ok) throw new Error('collect-email failed: ' + res.status);
      setSent(true);
    } catch (err) {
      console.error('Failed to save email:', err);
      setFailed(true);
    }
    setBusy(false);
  };

  return (
    <div className="prop-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="prop-card" role="dialog" aria-modal="true">
        <button className="x" aria-label="Close" onClick={onClose}>{I.x}</button>
        {!hasConversation ? (
          <div className="prop-no-chat">
            <span className="seal">{I.doc2}</span>
            <h3>{t.noChatH3}</h3>
            <p className="sub">{t.noChatSub}</p>
            <button className="btn btn-solid btn-sm" type="button" onClick={onClose} style={{ marginTop: 4 }}>{t.startChatting} {I.arrow}</button>
          </div>
        ) : !sent ? (
          <React.Fragment>
            <span className="seal">{I.doc2}</span>
            <h3>{t.propH3}</h3>
            <p className="sub">{t.propSub}</p>
            <form className="prop-field" onSubmit={submit}>
              <input type="email" value={email} placeholder={t.emailPh}
                onChange={(e) => setEmail(e.target.value)} autoFocus />
              <button type="submit" disabled={!valid || busy}>{busy ? t.sending : t.send} {I.arrow}</button>
            </form>
            {failed && <p className="prop-error">{t.sendError}</p>}
            <p className="prop-fine">{t.propFine}</p>
          </React.Fragment>
        ) : (
          <div className="prop-success">
            <span className="check">{I.check}</span>
            <h3>{t.sentH3}</h3>
            <p className="sub">{t.sentSub(email.trim())}</p>
            <button className="btn btn-solid btn-sm" type="button" onClick={onClose} style={{ marginTop: 4 }}>{t.backToChat}</button>
          </div>
        )}
      </div>
    </div>
  );
}

function AtelierChat() {
  const lang = useLang();
  const t = T[lang];
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const [flew, setFlew] = React.useState(false);
  const [showProp, setShowProp] = React.useState(false);
  const [nudged, setNudged] = React.useState(false);
  const scrollRef = React.useRef(null);
  const timers = React.useRef([]);
  const convo = React.useRef([]);
  const stageRef = React.useRef('initial');
  const emailRef = React.useRef(undefined);
  const langRef = React.useRef(lang);
  langRef.current = lang;

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

  React.useEffect(() => {
    const q = new URLSearchParams(window.location.search).get('q');
    if (q) setInput(decodeURIComponent(q));
  }, []);

  const userCount = messages.filter((m) => m.who === 'user').length;
  React.useEffect(() => {
    if (!nudged && userCount >= 2 && !typing) {
      const id = setTimeout(() => { setShowProp(true); setNudged(true); }, 900);
      timers.current.push(id);
      return () => clearTimeout(id);
    }
  }, [userCount, typing, nudged]);
  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages, typing]);

  const now = () => {
    const d = new Date();
    return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0');
  };

  const sendText = (raw) => {
    const text = (raw || '').trim();
    if (!text || typing) return;
    setFlew(true);
    timers.current.push(setTimeout(() => setFlew(false), 420));
    setMessages((m) => [...m, { who: 'user', text, time: now() }]);
    setInput('');
    setTyping(true);
    convo.current.push({ role: 'user', content: text });

    const pushBot = (reply) => {
      setTyping(false);
      setMessages((m) => [...m, { who: 'bot', text: reply, time: now() }]);
      convo.current.push({ role: 'assistant', content: reply });
    };

    fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: text,
        conversationHistory: convo.current,
        conversationStage: stageRef.current,
        userEmail: emailRef.current,
        language: langRef.current,
      }),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data && data.success && data.message) {
          if (data.conversationStage) stageRef.current = data.conversationStage;
          if (data.userEmail) emailRef.current = data.userEmail;
          pushBot(data.message);
          if (data.conversationComplete) {
            timers.current.push(setTimeout(() => {
              setMessages((m) => [...m, { who: 'bot', text: T[langRef.current].farewell, time: now() }]);
            }, 1400));
          }
        } else {
          pushBot((data && data.message) || T[langRef.current].fallback);
        }
      })
      .catch((err) => {
        console.error('Chat error:', err);
        timers.current.push(setTimeout(() => pushBot(T[langRef.current].fallback), 600));
      });
  };

  const onSubmit = (e) => { e.preventDefault(); sendText(input); };
  const started = messages.length > 0 || typing;

  return (
    <div className="chat-wrap" data-screen-label="Consultation chat">
      <div className="chat-bar">
        <div className="who">
          <span className="mk">{NZ_MARK}</span>
          <div>
            <div className="nm">NAZARBAN</div>
            <div className="sb">{t.consultant}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
          <button className="chat-propbtn" onClick={() => setShowProp(true)}>{I.doc2} {t.getProposal}</button>
          <span className="chat-status"><span className="dot"></span>{t.online}</span>
        </div>
      </div>

      <div className="chat-scroll" ref={scrollRef}>
        {!started && (
          <div className="chat-welcome">
            <span className="chat-seal"><span className="ring"></span>{NZ_MARK}</span>
            <span className="eyebrow center">{t.welcomeEyebrow}</span>
            <h2>{t.welcomeH2}</h2>
            <p>{t.welcomeP}</p>
            <span className="chat-rule"></span>
            <div className="chat-chips">
              {t.prompts.map((label, idx) => (
                <button className="chat-chip" key={idx} onClick={() => sendText(label)}>
                  <span className="ci">{PROMPT_ICONS[idx]}</span>
                  {label}
                  <span className="ck">{I.arrow}</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {messages.map((m, i) => (
          <div className={'chat-msg ' + m.who} key={i}>
            <span className="chat-av">{m.who === 'bot' ? NZ_MARK : 'YOU'}</span>
            <div className="chat-bubble">{m.text}</div>
          </div>
        ))}

        {typing && (
          <div className="chat-msg bot">
            <span className="chat-av">{NZ_MARK}</span>
            <div className="chat-typing"><i></i><i></i><i></i></div>
          </div>
        )}
      </div>

      {showProp && <ProposalPopup onClose={() => setShowProp(false)} getConversation={() => convo.current} hasConversation={started} />}

      <div className="chat-dock">
        <form className="chat-inputwrap" onSubmit={onSubmit}>
          <input
            className="chat-input"
            value={input}
            placeholder={t.inputPh}
            onChange={(e) => setInput(e.target.value)}
          />
          <button className={'chat-send' + (flew ? ' flew' : '')} type="submit"
            aria-label="Send" disabled={!input.trim() || typing}>
            {I.send}
          </button>
        </form>
        <div className="chat-foot">
          <a href="mailto:info@nazarbanai.com">{I.mail} info@nazarbanai.com</a>
          <a href="https://wa.me/19165870145" target="_blank" rel="noopener">{I.phone} WhatsApp</a>
        </div>
      </div>
    </div>
  );
}

window.AtelierChat = AtelierChat;
