// LeadForge AI Chatbot — Forge
// Uses window.claude.complete() with a LeadForge knowledge base.

const LEADFORGE_SYSTEM = `You are Forge, the friendly AI assistant for LeadForge Studio — a South African digital agency that builds websites and AI chatbots for small businesses.

PRICING:
- Starter Package: R1,400 once-off. Includes a 1 to 3 page professional website, WhatsApp button, Google Maps integration, contact form, mobile responsive design, and basic SEO. Delivered in 3 to 5 days.
- Growth Package: R3,000 once-off. Includes everything in Starter plus an AI chatbot that answers customer questions 24/7, and a simple booking calendar. Delivered in 5 to 7 days.
- Care Plan: R400 per month. Keeps the website live, updated, and running smoothly.

SERVICES:
1. Website Design: professional, mobile-first websites built to convert visitors into customers.
2. AI Chatbots: trained on the business, answers customer questions 24/7, qualifies leads.
3. WhatsApp Automation: a one-tap button that connects customers directly to WhatsApp instantly.
4. SEO Optimization: local SEO, Google Business listing, technical fixes to rank higher.
5. Booking Systems: a simple calendar where customers pick a service, date, and time. No payment required. Business gets notified instantly.
6. Maintenance and Hosting: website stays live, updates are made when needed, WhatsApp support available. From R400 per month.

INDUSTRIES SERVED: Personal Trainers, Real Estate agents, Dentists, Barbershops, Beauty Salons, Restaurants, and most other small businesses.

PROCESS: Discovery Call, then Design and Development, then Launch, then Ongoing Support. Most projects are live within a week.

CONTACT: WhatsApp +27 74 771 1329 or email supportleadforge@gmail.com. Based in South Africa, works with clients remotely.

RULES:
- Keep answers short, friendly and helpful.
- Never use em-dashes in your responses.
- Use plain, simple language.
- If someone wants to get started or has complex questions, encourage them to book a free consultation by clicking "Book Free Consultation" at the top of the page, or to WhatsApp us at +27 74 771 1329.
- Do not make up information not listed above.
- If asked something you do not know about LeadForge, say you are not sure and suggest contacting the team directly.`;

const GREETING = "Hi there! I'm Forge, LeadForge's AI assistant.\n\nI can answer questions about our services, pricing, and how we work. What would you like to know?";

async function callAI(messages) {
  var history = messages.map(function(m) {
    return { role: m.role === 'assistant' ? 'assistant' : 'user', content: m.content };
  });

  // Ensure conversation starts with a user message (required by the API)
  while (history.length > 0 && history[0].role !== 'user') {
    history.shift();
  }
  if (history.length === 0) throw new Error('No user message found.');

  // 1. Try the Vercel serverless endpoint (works on the live site)
  try {
    var res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: history, system: LEADFORGE_SYSTEM })
    });
    if (res.ok) {
      var data = await res.json();
      if (data.reply) return data.reply;
    }
  } catch (e) {
    // /api/chat not available — fall through to window.claude
  }

  // 2. Fall back to window.claude (Claude Design environment only)
  if (window.claude) {
    var reply = await window.claude.complete({
      system: LEADFORGE_SYSTEM,
      messages: history
    });
    return reply;
  }

  throw new Error('AI not available');
}

function ChatbotWidget() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
  { role: 'assistant', content: GREETING }]
  );
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const msgsRef = React.useRef(null);
  const inputRef = React.useRef(null);

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

  React.useEffect(() => {
    if (open && inputRef.current) {
      setTimeout(() => inputRef.current && inputRef.current.focus(), 100);
    }
  }, [open]);

  async function send() {
    const text = input.trim();
    if (!text || loading) return;
    setInput('');
    setError(null);
    const newMessages = [...messages, { role: 'user', content: text }];
    setMessages(newMessages);
    setLoading(true);

    try {
      const reply = await callAI(newMessages);
      setMessages(function (prev) {
        return [...prev, { role: 'assistant', content: reply }];
      });
    } catch (e) {
      setMessages(function (prev) {
        return [...prev, {
          role: 'assistant',
          content: "Sorry, I couldn't connect right now. Please message us on WhatsApp at +27 74 771 1329 and we'll get back to you quickly."
        }];
      });
    }
    setLoading(false);
  }

  function handleKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  }

  function toggleOpen() {
    setOpen(function (o) {return !o;});
  }

  return (
    <React.Fragment>
      {open &&
      <div className="cb-panel">
          <div className="cb-head">
            <div className="cb-head-info">
              <span className="cb-avatar">F</span>
              <div>
                <strong>Forge</strong>
                <span>LeadForge AI · online</span>
              </div>
            </div>
            <button className="cb-close" onClick={toggleOpen} aria-label="Close chat">&#215;</button>
          </div>

          <div className="cb-messages" ref={msgsRef}>
            {messages.map(function (m, i) {
            return (
              <div key={i} className={"cb-msg " + (m.role === 'user' ? 'cb-msg-user' : 'cb-msg-bot')}>
                  {m.content}
                </div>);

          })}
            {loading &&
          <div className="cb-msg cb-msg-bot cb-loading">
                <span></span><span></span><span></span>
              </div>
          }
          </div>

          <div className="cb-input-row">
            <input
            ref={inputRef}
            className="cb-input"
            value={input}
            onChange={function (e) {setInput(e.target.value);}}
            onKeyDown={handleKey}
            placeholder="Ask about pricing or services..."
            disabled={loading}
            autoComplete="off" />
          
            <button className="cb-send" onClick={send} disabled={loading || !input.trim()} aria-label="Send">
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <path d="M2 8h10M8 4l4 4-4 4" />
              </svg>
            </button>
          </div>
          <div className="cb-footer">Powered by AI. For complex questions, <a href="https://wa.me/27747711329" target="_blank" rel="noopener" style={{ color: 'inherit', textDecoration: 'underline' }}>chat on WhatsApp</a>.</div>
        </div>
      }

      <button
        className={"cb-toggle" + (open ? " cb-toggle-open" : "")}
        onClick={toggleOpen}
        aria-label={open ? "Close chat" : "Chat with Forge AI"}>

        {open ? (
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M18 6 6 18M6 6l12 12"/>
          </svg>
        ) : (
          <svg viewBox="0 0 28 28" width="28" height="28" fill="none" aria-hidden="true">
            {/* Head */}
            <rect x="4" y="9" width="20" height="14" rx="4"
              fill="rgba(255,255,255,0.1)" stroke="rgba(255,255,255,0.75)" strokeWidth="1.4"/>
            {/* Left ear */}
            <rect x="2" y="13.5" width="2.5" height="3.5" rx="1" fill="rgba(255,255,255,0.35)"/>
            {/* Right ear */}
            <rect x="23.5" y="13.5" width="2.5" height="3.5" rx="1" fill="rgba(255,255,255,0.35)"/>
            {/* Left eye */}
            <rect className="robot-eye" x="7.5" y="13" width="4" height="3.5" rx="1.2"
              fill="white" style={{transformBox:'fill-box', transformOrigin:'center'}}/>
            {/* Right eye */}
            <rect className="robot-eye robot-eye-r" x="16.5" y="13" width="4" height="3.5" rx="1.2"
              fill="white" style={{transformBox:'fill-box', transformOrigin:'center'}}/>
            {/* Mouth */}
            <path d="M10.5 20.5h7" stroke="rgba(255,255,255,0.55)" strokeWidth="1.4" strokeLinecap="round"/>
            {/* Antenna stem */}
            <line x1="14" y1="9" x2="14" y2="5.5"
              stroke="rgba(255,255,255,0.65)" strokeWidth="1.3" strokeLinecap="round"/>
            {/* Antenna tip glow ring */}
            <circle cx="14" cy="4.5" r="2.4" fill="#10b981" opacity="0.25"
              className="antenna-pulse" style={{transformBox:'fill-box', transformOrigin:'center'}}/>
            {/* Antenna tip */}
            <circle cx="14" cy="4.5" r="1.6" fill="#10b981"/>
          </svg>
        )}
      </button>
    </React.Fragment>);

}

ReactDOM.createRoot(document.getElementById('chatbot-root')).render(<ChatbotWidget />);