// chatbot.jsx — Jawwad's AI assistant widget

const CW_SYSTEM = `You are the AI assistant on Jawwad's automation portfolio website. Help visitors understand his services, convince them to book a free audit, and answer questions. Be direct and confident — not salesy.

WHO JAWWAD IS:
- Automation specialist, Karachi (GMT+5), works globally
- Builds ready-to-use automation systems — working systems delivered, not slide decks
- Specializes in: workflow automation, AI automation, no-code (Make/n8n/Zapier), API integrations, CRM automation, email workflows, reporting dashboards, custom backends, webhooks, databases (Postgres/Airtable), internal tools

HOW HE WORKS:
1. Free 30-min audit call — understand the problem, no commitment
2. Scope doc — what gets built, timeline, exact cost
3. Build — Jawwad builds it solo, fast, keeps client in the loop
4. Deliver — working system + plain-English docs, no technical knowledge needed to use it
5. Post-delivery support for tweaks

SERVICES & PRICING:
- Starter automation: single workflow, under $1k, 3–5 days
- Business workflow: full process automated end-to-end, $1k–$3k, 1–2 weeks
- Custom system: backend + dashboard + integrations, $3k–$8k+, 2–4 weeks
- Free 30-min audit: no cost, no commitment — you leave with a real automation plan
- Only charged after a 1-month trial (zero financial risk)

TOOLS:
- No-code: Make, n8n, Zapier
- AI: OpenAI, Claude, custom prompts
- Backend: Node.js, Python, PostgreSQL
- Glue: Webhooks, REST APIs, Cron jobs
- Dashboards: Retool, custom React

COMMON PROJECTS JAWWAD HAS BUILT:
- Lead capture → CRM entry → auto follow-up email sequence
- AI inbox triage: reads emails, tags, drafts replies
- Client onboarding: form fills CRM + sends welcome sequence + creates project folder
- Weekly reporting: pulls from 3 platforms, merges, emails formatted summary
- Booking automation: Calendly → CRM → prep email → reminder
- Internal ops tools: dashboards that update in real time from Sheets/Airtable
- Data sync between platforms that don't natively connect

DIFFERENTIATORS:
- You receive a working system, not a recommendation doc
- Tool-flexible: no-code when it fits, custom code when it doesn't
- Client-friendly: you use it without needing to read the implementation
- Scalable: a no-code start can become a custom backend without throwing work away
- Every system ships with plain-language documentation
- Response within 24 hours

CONTACT:
- WhatsApp: https://wa.me/923021044751 (fastest)
- Email: hello@jawwadautomation.org
- Book free audit: scroll to the contact form on this page (bottom of site)

FAQS:
Q: How long does it take?
A: Starter (single workflow): 3–5 days. Business workflow: 1–2 weeks. Custom system: 2–4 weeks.

Q: Do I need to be technical?
A: No. Systems ship with plain-language docs. You click buttons, not code.

Q: What if I don't know what I need?
A: That's what the free audit is for. 30 minutes, Jawwad listens, you leave with a clear plan and no obligation.

Q: Do you work with small businesses?
A: Yes. Most clients are founders or small teams doing too much by hand.

Q: Can you integrate with [specific tool]?
A: Almost certainly. Make/n8n/Zapier connect to 1000+ apps. For anything custom, Jawwad builds direct API integrations.

Q: What if the automation breaks?
A: Jawwad builds with error handling and monitoring. Post-delivery support is included for 30 days.

Q: Is there a cheaper option?
A: Yes — a single Zapier/Make flow can be under $500 and done in 2–3 days.

Q: Can I see examples?
A: Yes — scroll up on this page to the "Systems" and "Case Studies" sections for real examples.

TONE RULES:
- Short answers — 2–4 sentences max unless more detail is asked for
- Never use words like: synergy, leverage, passionate, results-driven, dynamic, innovative
- Always guide toward booking the free audit when relevant
- Be warm, direct, and helpful — like a knowledgeable colleague, not a salesperson
- If asked about pricing, give a real number range, not "it depends"
- Never say "I can't help with that"`;

const CW_QUICK = [
  'What do you automate?',
  'How much does it cost?',
  'How long does it take?',
  'Book a free audit',
];

const ChatWidget = () => {
  const [open, setOpen]       = React.useState(false);
  const [msgs, setMsgs]       = React.useState([{
    role: 'assistant',
    content: "Hi 👋 I'm Jawwad's assistant. Ask me anything — services, pricing, timelines, or whether your process can be automated."
  }]);
  const [input, setInput]     = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showQuick, setShowQuick] = React.useState(true);
  const [unread, setUnread]   = React.useState(true);
  const bottomRef = React.useRef(null);
  const inputRef  = React.useRef(null);

  React.useEffect(() => {
    if (open) { setUnread(false); setTimeout(() => inputRef.current?.focus(), 80); }
  }, [open]);

  React.useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [msgs, loading]);

  const send = async (text) => {
    const msg = (text || input).trim();
    if (!msg || loading) return;
    setInput('');
    setShowQuick(false);
    const next = [...msgs, { role: 'user', content: msg }];
    setMsgs(next);
    setLoading(true);
    try {
      const reply = await window.ai.complete([
        { role: 'system', content: CW_SYSTEM },
        ...next.map(m => ({ role: m.role, content: m.content }))
      ]);
      setMsgs(prev => [...prev, { role: 'assistant', content: reply }]);
    } catch {
      setMsgs(prev => [...prev, {
        role: 'assistant',
        content: "Something went wrong on my end. Reach Jawwad directly on WhatsApp: wa.me/923021044751 — he responds within hours."
      }]);
    }
    setLoading(false);
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  };

  // Linkify URLs in assistant messages
  const linkify = (text) => {
    const parts = text.split(/(https?:\/\/[^\s]+)/g);
    return parts.map((p, i) =>
      p.startsWith('http')
        ? <a key={i} href={p} target="_blank" rel="noopener" className="cw-link">{p}</a>
        : p
    );
  };

  return (
    <>
      {open && (
        <div className="cw-panel">
          {/* Header */}
          <div className="cw-header">
            <div className="cw-avatar">J</div>
            <div className="cw-hinfo">
              <div className="cw-hname">Jawwad's Assistant</div>
              <div className="cw-hstatus"><span className="cw-online-dot" />Online now</div>
            </div>
            <button className="cw-close" onClick={() => setOpen(false)} aria-label="Close">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
              </svg>
            </button>
          </div>

          {/* Messages */}
          <div className="cw-messages">
            {msgs.map((m, i) => (
              <div key={i} className={`cw-msg ${m.role === 'user' ? 'cw-user' : 'cw-bot'}`}>
                {m.role === 'assistant' ? linkify(m.content) : m.content}
              </div>
            ))}

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

            {showQuick && !loading && msgs.length <= 1 && (
              <div className="cw-quick">
                {CW_QUICK.map(q => (
                  <button key={q} className="cw-quick-btn" type="button" onClick={() => send(q)}>
                    {q}
                  </button>
                ))}
              </div>
            )}

            <div ref={bottomRef} />
          </div>

          {/* Input */}
          <div className="cw-input-row">
            <input
              ref={inputRef}
              className="cw-input"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={onKey}
              placeholder="Ask anything…"
              disabled={loading}
            />
            <button className="cw-send" onClick={() => send()}
              disabled={loading || !input.trim()} aria-label="Send">
              <svg width="15" height="15" viewBox="0 0 16 16" fill="none">
                <path d="M14.5 8L1.5 1.5l2.8 6.5-2.8 6.5L14.5 8z" fill="currentColor"/>
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* FAB */}
      <button className={`cw-fab ${open ? 'cw-fab-active' : ''}`}
        onClick={() => setOpen(o => !o)} aria-label="Chat with Jawwad's assistant">
        {open
          ? <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
              <path d="M1 1l16 16M17 1L1 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
            </svg>
          : <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2v10z"
                stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
        }
        {!open && unread && <span className="cw-badge" />}
      </button>
    </>
  );
};

window.ChatWidget = ChatWidget;
