/* eslint-disable */
// Floating chat widgets — a WhatsApp launcher and a website-aware AI assistant.
//
//   <WhatsAppButton number="599XXXXXXX" />   — opens wa.me with a preset message
//   <AIChatWidget />                          — full chat panel powered by claude.complete
//
// Both float bottom-left so they don't collide with the Tweaks panel (bottom-right).

// ─────────────────────────────────────────────────────────────────────────────
// Knowledge-base — facts the AI gets in its system prompt. Update this when
// the catalog or directory changes substantially.
// ─────────────────────────────────────────────────────────────────────────────

const CBM_KNOWLEDGE = `
You are the official AI assistant for Curaçao Business Magazine (CBM, cbm.cw),
Curaçao's premier digital business publication. You answer questions about the
publication, the courses, jobs, business directory and advertising on the site.
Be concise, accurate, and use only the information below. If a question is
outside this scope, politely say you can connect them with the editorial team
at hello@cbm.cw or via WhatsApp.

# About CBM
- Digital-only publication (no print). Five channels: website, newsletter,
  social, video, events.
- Audience: 25,000+ monthly readers, 15,000+ social followers,
  8,000+ newsletter subscribers, 12,000+ engaged business readers.
- Official media partner of the Curaçao Chamber of Commerce & Industry (KvK / KKN).
- Six brand pillars: Connect, Inform, Inspire, Promote, Empower, Elevate Curaçao.
- Available in English, Dutch, Papiamentu, Spanish, German.
- Currency: XCG (Caribbean guilder, pegged 1 USD ≈ 1.79 XCG). Prices shown in
  both XCG and USD.

# Sections of the site
1. **News / Editorial** — leadership, innovation, investment articles.
2. **Directory** — verified business directory of Curaçao companies, by sector.
   Listings free for verified companies; Featured (XCG 250/yr) and Showcase
   (XCG 750/yr) tiers also available.
3. **Jobs** — senior and specialist roles. Companies can post jobs:
   Standard XCG 350, Featured XCG 750, Headline XCG 1,500 (30 days each).
4. **Courses** — on-demand business courses (taught by Curaçao operators).
   Single-purchase from ~XCG 195 to XCG 495. Membership: Monthly XCG 95,
   Yearly XCG 950 (saves 17%), Team XCG 850/seat/yr (5+ seats).
5. **Advertise** — sponsorship packages for brands wanting reach:
   - Silver XCG 1,250/mo — sponsored article, banner, social shoutout, newsletter.
   - Gold XCG 2,500/mo — 2× sponsored, premium banner, social promo, sponsored post.
   - Platinum XCG 4,500/mo — 4× sponsored, site takeover, social campaign, video.

# Courses currently in the library (with single-purchase prices)
- Starting a Business in Curaçao — XCG 295 — beginner — 10 modules — Mireille de Windt
- The CFO Toolkit — XCG 495 — advanced — 8 modules — Ronald Pourier
- Digital Marketing for the Caribbean — XCG 245 — intermediate — Anouk Martijn
- Leadership in Island Business — XCG 345 — Glenn Camelia
- SME Finance Fundamentals — XCG 195 — beginner — Sharine Rojer
- Sustainability Strategy for Caribbean Businesses — XCG 395 — Alex de Boer
- Curaçao Tax for Business Owners — XCG 295 — Eric Brouwer (KPMG)
- Public Speaking for Executives — XCG 195 — Linda Boertien
- HR Fundamentals for Curaçao Employers — XCG 245 — Marlene Sluis

# Contact
- Editorial: editorial@cbm.cw
- Partnerships / advertising: partners@cbm.cw
- WhatsApp: +599 9 555 0123 (Mon–Fri, 09:00–17:00 AST)

# Style
- Direct, declarative tone. No emoji. No exclamation marks.
- Use the user's own language (English / Dutch / Papiamentu / Spanish / German).
- Always spell Curaçao with the cedilla.
- Keep answers under 4 sentences unless the user asks for detail.
- If recommending a course, job or business, link the relevant section
  (e.g. "see the Courses tab").
`.trim();

// ─────────────────────────────────────────────────────────────────────────────
// WhatsApp button
// ─────────────────────────────────────────────────────────────────────────────

const WhatsAppIcon = ({ size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="currentColor" aria-hidden="true">
    <path d="M16.001 4C9.373 4 4 9.373 4 16c0 2.121.555 4.116 1.527 5.847L4 28l6.299-1.479A11.95 11.95 0 0 0 16 28c6.627 0 12-5.373 12-12S22.628 4 16.001 4Zm0 21.818a9.79 9.79 0 0 1-4.99-1.37l-.358-.213-3.738.878.886-3.646-.234-.376a9.789 9.789 0 0 1-1.522-5.272c0-5.41 4.404-9.814 9.815-9.814 2.622 0 5.087 1.022 6.943 2.878a9.747 9.747 0 0 1 2.876 6.943c0 5.41-4.404 9.814-9.814 9.814Zm5.379-7.342c-.296-.148-1.751-.864-2.022-.963-.272-.099-.469-.148-.667.148-.198.296-.766.963-.94 1.161-.173.198-.346.222-.642.074-.296-.148-1.25-.461-2.381-1.469-.88-.785-1.475-1.755-1.647-2.05-.173-.296-.018-.456.13-.604.133-.133.296-.346.444-.519.148-.173.198-.296.296-.494.099-.198.05-.371-.025-.519-.074-.148-.667-1.608-.914-2.202-.241-.578-.486-.5-.667-.51l-.567-.01a1.09 1.09 0 0 0-.79.371c-.272.296-1.037 1.013-1.037 2.471 0 1.458 1.062 2.866 1.21 3.064.148.198 2.094 3.197 5.072 4.485.709.306 1.262.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.751-.715 1.998-1.405.247-.69.247-1.281.173-1.405-.074-.124-.272-.198-.568-.346Z"/>
  </svg>
);

const WhatsAppButton = ({ number = '5999555 0123', message }) => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const cleanNumber = number.replace(/\D/g, '');
  const msg = encodeURIComponent(message || t('chat_whatsapp_prefill') || "Hi CBM — I have a question about");
  const href = 'https://wa.me/' + cleanNumber + '?text=' + msg;
  return (
    <a
      className="cbm-fab cbm-fab--whatsapp"
      href={href}
      target="_blank"
      rel="noopener"
      title={t('chat_whatsapp_label') || 'WhatsApp'}
      aria-label={t('chat_whatsapp_label') || 'WhatsApp'}
    >
      <WhatsAppIcon size={22} />
      <span className="cbm-fab__label">{t('chat_whatsapp_label') || 'WhatsApp'}</span>
    </a>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// AI chat — site-aware assistant powered by window.claude.complete
// ─────────────────────────────────────────────────────────────────────────────

const SUGGESTED = [
  'Which course should a first-time founder start with?',
  'What\u0027s in the Gold advertising package?',
  'Show me CFO and finance roles.',
  'How do I list my business?',
];

const AIChatWidget = () => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const { lang } = (window.useLang && window.useLang()) || { lang: 'en' };

  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([]); // {role:'user'|'assistant', text}
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const ask = async (text) => {
    if (!text || busy) return;
    const userMsg = { role: 'user', text };
    setMessages(m => [...m, userMsg]);
    setInput('');
    setBusy(true);

    const history = [...messages, userMsg]
      .map(m => (m.role === 'user' ? 'User' : 'Assistant') + ': ' + m.text)
      .join('\n\n');

    const langName = ({en:'English', nl:'Dutch', pap:'Papiamentu', es:'Spanish', de:'German'})[lang] || 'English';
    const prompt = CBM_KNOWLEDGE +
      '\n\n# Conversation so far\n' + history +
      '\n\n# Instructions\nReply in ' + langName +
      '. Keep it under 4 sentences unless the user asks for more detail.';

    let reply = '';
    try {
      if (window.claude && window.claude.complete) {
        reply = await window.claude.complete(prompt);
      } else {
        reply = "(AI is offline — this prototype needs the claude.complete bridge.)";
      }
    } catch (err) {
      reply = "Sorry — something went wrong. Try again, or reach our editorial team at editorial@cbm.cw.";
    }

    setMessages(m => [...m, { role: 'assistant', text: (reply || '').trim() }]);
    setBusy(false);
  };

  const clear = () => setMessages([]);

  return (
    <>
      <button
        className={'cbm-fab cbm-fab--ai' + (open ? ' is-open' : '')}
        onClick={() => setOpen(o => !o)}
        title={t('chat_ai_label') || 'Ask CBM AI'}
        aria-label={t('chat_ai_label') || 'Ask CBM AI'}
      >
        {open
          ? <i data-lucide="x" style={{width: 22, height: 22}}></i>
          : <i data-lucide="sparkles" style={{width: 22, height: 22}}></i>}
        {!open && <span className="cbm-fab__label">{t('chat_ai_label') || 'Ask CBM AI'}</span>}
      </button>

      {open && (
        <div className="cbm-chat" role="dialog" aria-label="CBM AI assistant">
          <header className="cbm-chat__head">
            <div className="cbm-chat__brand">
              <div className="cbm-chat__bot"><i data-lucide="sparkles"></i></div>
              <div>
                <div className="cbm-chat__title">{t('chat_ai_title') || 'CBM Assistant'}</div>
                <div className="cbm-chat__status">
                  <span className="cbm-chat__dot" />
                  {t('chat_ai_status') || 'Online · trained on cbm.cw'}
                </div>
              </div>
            </div>
            <div className="cbm-chat__head-actions">
              {messages.length > 0 && (
                <button className="cbm-chat__head-btn" onClick={clear} title={t('chat_clear') || 'Clear chat'}>
                  <i data-lucide="rotate-ccw" style={{width: 14, height: 14}}></i>
                </button>
              )}
              <button className="cbm-chat__head-btn" onClick={() => setOpen(false)} aria-label="Close">
                <i data-lucide="x" style={{width: 16, height: 16}}></i>
              </button>
            </div>
          </header>

          <div className="cbm-chat__body" ref={scrollRef}>
            {messages.length === 0 && (
              <>
                <div className="cbm-chat__greeting">
                  <p>{t('chat_ai_intro') || "Hi — I'm trained on cbm.cw. Ask me about courses, jobs, the business directory or advertising on CBM."}</p>
                </div>
                <div className="cbm-chat__suggestions">
                  {SUGGESTED.map(s => (
                    <button key={s} className="cbm-chat__suggestion" onClick={() => ask(s)}>
                      {s}
                    </button>
                  ))}
                </div>
              </>
            )}
            {messages.map((m, i) => (
              <div key={i} className={'cbm-chat__msg cbm-chat__msg--' + m.role}>
                {m.role === 'assistant' && <div className="cbm-chat__bot cbm-chat__bot--sm"><i data-lucide="sparkles"></i></div>}
                <div className="cbm-chat__bubble">{m.text}</div>
              </div>
            ))}
            {busy && (
              <div className="cbm-chat__msg cbm-chat__msg--assistant">
                <div className="cbm-chat__bot cbm-chat__bot--sm"><i data-lucide="sparkles"></i></div>
                <div className="cbm-chat__bubble cbm-chat__bubble--typing">
                  <span></span><span></span><span></span>
                </div>
              </div>
            )}
          </div>

          <form className="cbm-chat__compose" onSubmit={e => { e.preventDefault(); ask(input); }}>
            <input
              type="text"
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder={t('chat_ai_placeholder') || 'Ask anything about CBM…'}
              disabled={busy}
            />
            <button type="submit" disabled={busy || !input.trim()} aria-label="Send">
              <i data-lucide="arrow-up" style={{width: 18, height: 18}}></i>
            </button>
          </form>
          <div className="cbm-chat__foot">
            {t('chat_ai_disclaimer') || 'AI replies may be imperfect. For anything important, contact editorial@cbm.cw.'}
          </div>
        </div>
      )}
    </>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
// Cluster — both widgets, stacked bottom-left
// ─────────────────────────────────────────────────────────────────────────────

const ChatCluster = () => {
  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  });
  return (
    <div className="cbm-fab-cluster">
      {/* Both chat surfaces hidden until configured. Re-enable by uncommenting
          the relevant line below.

          AI chat — needs an Anthropic API key + the cbm-ai-chat Worker deployed
                    (see workers/cbm-ai-chat/README.md). Then uncomment:
          <AIChatWidget />

          WhatsApp — needs the real CBM business number. Then uncomment:
          <WhatsAppButton number="5999XXXXXXX" />
      */}
    </div>
  );
};

Object.assign(window, { WhatsAppButton, AIChatWidget, ChatCluster });
