// Winkz Designs 2026, real live AI chat widget (calls window.claude.complete)
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;
  const GRAD = 'linear-gradient(120deg,#F23BFE,#79BAFF,#2DE3EA)';

  const SYSTEM = `You are the Winkz Designs assistant, a friendly, sharp concierge for a website & AI design agency.
Winkz Designs builds: custom websites, brand identity, immersive/3D build-outs, custom CRMs, client portals, AI automations, workflow integrations, internal tools, dashboards, AI SEO, AI support chat + voice agents, Google Workspace setup and business verification.
Positioning: we design the sites, custom tools and AI systems that fill the gaps and inefficiencies in a business. Unlike big monthly SaaS, our software is simple, custom-built to the client (no templates), integrated from day one, secure on their own accounts, and fully owned by them, no lock-in. Discovery is free and clients pay only once satisfied with each phase; intro calls are 30 min and free.
Contact: design@winkzdesigns.com, +1 (302) 932-3352, based in Tampa, Florida, remote worldwide.
Answer in 1-3 short sentences, warm and concrete. When it fits, invite them to book a free intro call. Never invent specific prices, say it's scoped up front, free discovery. Only discuss Winkz and what a business might need.`;

  const FALLBACK = "Happy to help, though that one's better answered live. Email design@winkzdesigns.com or book a free 30-minute intro call and we'll map exactly what your business needs.";
  const SUGGEST = ['What do you build?', 'How much does it cost?', 'Do I own the software?'];

  /* ── Offline brain ─────────────────────────────────────────────────────────
     Runs when no AI endpoint is reachable (plain static hosting). Keyword-scored
     intents so the widget still answers real questions instead of erroring out. */
  const KB = [
    { k: ['what do you build', 'what do you do', 'services', 'offer', 'help with', 'specialize', 'expertise'],
      a: "We build custom websites, brand identity, custom CRMs and internal tools, AI support chat and voice agents, automations, and AI SEO. Basically: the site plus the software behind it.",
      q: ['How much does it cost?', 'How long does it take?'] },
    { k: ['price', 'pricing', 'cost', 'how much', 'budget', 'quote', 'expensive', 'rate', 'charge'],
      a: "Every build is scoped and priced up front, no surprise line items, and discovery is free. Most projects land in a range we can give you on a 30-minute call once we know what you need.",
      q: ['Book a call', 'What do you build?'] },
    { k: ['how long', 'timeline', 'how fast', 'turnaround', 'when can', 'deadline', 'lead time'],
      a: "A focused site is usually 2 to 4 weeks; custom software and CRM builds run 4 to 10 weeks depending on scope. We work in phases so you see progress every week.",
      q: ['What is your process?', 'Book a call'] },
    { k: ['own', 'ownership', 'lock in', 'lock-in', 'my data', 'license', 'source code', 'subscription'],
      a: "You own it outright, code, data and accounts, all on your own infrastructure. No per-seat tax, no lock-in, no monthly SaaS bill for software you paid us to build.",
      q: ['How much does it cost?', 'Book a call'] },
    { k: ['process', 'how does it work', 'steps', 'get started', 'start', 'onboard', 'next step', 'kick off'],
      a: "Free discovery call, then a fixed scope, then design, then build in phases you approve as we go. You only pay for a phase once you're happy with it.",
      q: ['Book a call', 'Do I own the software?'] },
    { k: ['ai', 'automation', 'automate', 'agent', 'chatbot', 'chat bot', 'voice', 'gpt', 'llm'],
      a: "We build AI where it removes real work: support chat trained on your business, voice agents that answer and qualify calls, and automations that kill the copy-paste between your tools.",
      q: ['How much does it cost?', 'Book a call'] },
    { k: ['crm', 'software', 'internal tool', 'dashboard', 'portal', 'app', 'database', 'pipeline'],
      a: "Custom CRMs and internal tools built around how your team actually works, pipelines, dashboards, client portals and integrations, instead of bending your process to fit someone else's product.",
      q: ['Do I own the software?', 'How long does it take?'] },
    { k: ['seo', 'rank', 'google', 'traffic', 'found', 'search', 'keyword'],
      a: "We handle technical and content SEO, then tune your pages for AI search so you're the answer people get from ChatGPT and Google's AI results, not just a blue link.",
      q: ['How much does it cost?', 'Book a call'] },
    { k: ['website', 'web site', 'redesign', 'rebuild', 'landing page', 'new site', 'refresh'],
      a: "Custom designed and coded from scratch, never a template, fast, mobile-first, with a CMS so you can edit it yourself. Redesigns of dated sites are a big part of what we do.",
      q: ['How long does it take?', 'See your work'] },
    { k: ['brand', 'logo', 'identity', 'rebrand', 'guidelines', 'font', 'colors'],
      a: "Logo and identity system, color and type rules, and guidelines your whole team can actually use, so everything you publish looks like the same company.",
      q: ['How much does it cost?', 'Book a call'] },
    { k: ['ecommerce', 'e-commerce', 'store', 'shopify', 'checkout', 'sell online', 'product page'],
      a: "Yes, we build and rescue e-commerce, from storefront design and product pages through checkout, and we wire the analytics so you can see where sales leak.",
      q: ['How much does it cost?', 'Book a call'] },
    { k: ['amazon', 'fba', 'ungate', 'brand approval', 'gated'],
      a: "We build the brand websites Amazon accepts for FBA brand approval and ungating, done properly so your application isn't the reason it gets rejected.",
      q: ['How long does it take?', 'Book a call'] },
    { k: ['maintain', 'maintenance', 'support', 'host', 'hosting', 'update', 'after launch', 'retainer'],
      a: "Launch isn't the end. We offer ongoing maintenance, hosting help, monitoring and updates, or we hand it over clean if you'd rather run it yourself.",
      q: ['Book a call', 'What do you build?'] },
    { k: ['portfolio', 'work', 'examples', 'case study', 'clients', 'who have you'],
      a: "There's a portfolio on this site with real builds, Clarity HCM, 5 Hour Seller and more. Scroll to Work, or ask me what we did on any of them.",
      q: ['Book a call', 'How much does it cost?'] },
    { k: ['call', 'book', 'meeting', 'consult', 'talk to', 'schedule', 'appointment', 'demo'],
      a: "Let's do it, the intro call is free and takes 30 minutes. Hit Start your project, or email design@winkzdesigns.com and we'll send times.",
      q: ['What do you build?', 'How much does it cost?'] },
    { k: ['contact', 'email', 'phone', 'number', 'reach', 'get in touch'],
      a: "design@winkzdesigns.com or +1 (302) 932-3352. Either reaches us directly, usually same day.",
      q: ['Book a call'] },
    { k: ['where', 'located', 'location', 'city', 'remote', 'based', 'tampa', 'timezone'],
      a: "We're based in Tampa, Florida and work with clients remotely worldwide. Plenty of our projects never need a single in-person meeting.",
      q: ['Book a call', 'What do you build?'] },
    { k: ['who are you', 'about', 'team', 'company', 'founder', 'how long have you', 'experience'],
      a: "Winkz Designs is a website and AI design agency, 5+ years in, 150+ projects shipped. Small senior team, so you talk to the people actually building your project.",
      q: ['See your work', 'Book a call'] },
    { k: ['login', 'log in', 'sign in', 'portal', 'password', 'account'],
      a: "Client sign-in is the Client login link at the top right. Portal access is invite-only, your account manager sends credentials at kickoff, and we can resend them any time.",
      q: ['Contact', 'Book a call'] },
    { k: ['hi', 'hey', 'hello', 'yo', 'sup', 'good morning', 'good afternoon'],
      a: "Hey! What are you trying to build, or fix? I can talk websites, custom software, AI systems or pricing.",
      q: ['What do you build?', 'How much does it cost?'] },
    { k: ['thanks', 'thank you', 'appreciate', 'perfect', 'great', 'awesome', 'cool'],
      a: "Anytime. If you want the real answer for your situation, the free 30-minute call is the fastest way to get it.",
      q: ['Book a call'] },
  ];

  function offlineReply(text) {
    const t = ' ' + text.toLowerCase().replace(/[^a-z0-9\s'-]/g, ' ') + ' ';
    let best = null, bestScore = 0;
    for (const item of KB) {
      let score = 0;
      for (const k of item.k) if (t.indexOf(k) !== -1) score += k.indexOf(' ') !== -1 ? 3 : 2;
      if (score > bestScore) { bestScore = score; best = item; }
    }
    if (!best) return { a: "Good question, and I'd rather give you a real answer than a guess. Email design@winkzdesigns.com or book the free 30-minute call and we'll get specific about your business.", q: ['What do you build?', 'How much does it cost?', 'Book a call'] };
    return best;
  }

  function ChatWidget() {
    const [open, setOpen] = useState(false);
    const [msgs, setMsgs] = useState([{ role: 'assistant', content: "Hey! I'm the Winkz assistant. Ask me about websites, custom software, AI systems, or what we'd build for your business." }]);
    const [input, setInput] = useState('');
    const [busy, setBusy] = useState(false);
    const [chips, setChips] = useState([]);
    const [proxyOk, setProxyOk] = useState(null);
    const bodyRef = useRef(null);
    useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, busy, open]);

    async function send(text) {
      const q = (text != null ? text : input).trim();
      if (!q || busy) return;
      setInput('');
      const next = [...msgs, { role: 'user', content: q }];
      setMsgs(next); setBusy(true);
      setChips([]);
      const history = next.map(m => ({ role: m.role, content: m.content }));

      const think = (ms) => new Promise(r => setTimeout(r, ms));
      let reply = null;

      // 1. live model inside the design preview
      try {
        if (window.claude && window.claude.complete) {
          reply = await window.claude.complete({ system: SYSTEM, messages: history, max_tokens: 300 });
        }
      } catch (e) { reply = null; }

      // 2. server proxy (chat.php with the API key kept server-side)
      if (!reply && proxyOk !== false) {
        try {
          const res = await fetch('chat.php', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ system: SYSTEM, messages: history }),
          });
          if (res.ok) {
            const data = await res.json();
            if (data && data.reply) { reply = data.reply; setProxyOk(true); }
            else setProxyOk(false);
          } else setProxyOk(false);
        } catch (e) { setProxyOk(false); }
      }

      // 3. built-in offline brain, always answers
      if (!reply) {
        const local = offlineReply(q);
        await think(420 + Math.random() * 380);
        reply = local.a;
        setChips(local.q || []);
      }

      setMsgs(m => [...m, { role: 'assistant', content: String(reply).trim() || FALLBACK }]);
      setBusy(false);
    }

    return (
      <React.Fragment>
        {/* launcher */}
        <button onClick={() => setOpen(o => !o)} aria-label="Chat with Winkz" style={{
          position: 'fixed', right: 24, bottom: 24, zIndex: 200, width: 58, height: 58, borderRadius: 999,
          border: 'none', cursor: 'pointer', background: GRAD, boxShadow: '0 16px 40px -12px rgba(242,59,254,0.6)',
          display: 'grid', placeItems: 'center', transition: 'transform .3s cubic-bezier(.16,1,.3,1)', transform: open ? 'scale(0.9)' : 'scale(1)',
        }}>
          <Icon n={open ? 'X' : 'MessageCircle'} s={24} color="#08080A" strokeWidth={2.2} />
        </button>

        {/* panel */}
        <div style={{
          position: 'fixed', right: 24, bottom: 92, zIndex: 200, width: 'min(370px, calc(100vw - 32px))',
          height: open ? 'min(520px, calc(100vh - 130px))' : 0, opacity: open ? 1 : 0,
          transform: open ? 'none' : 'translateY(16px) scale(0.98)', transformOrigin: 'bottom right',
          transition: 'opacity .35s ease, transform .35s cubic-bezier(.16,1,.3,1), height .35s ease',
          pointerEvents: open ? 'auto' : 'none', overflow: 'hidden',
          borderRadius: 20, border: '1px solid rgba(255,255,255,0.12)', background: 'rgba(12,12,15,0.97)',
          backdropFilter: 'blur(16px)', boxShadow: '0 40px 90px -30px rgba(0,0,0,0.85)', display: 'flex', flexDirection: 'column',
        }}>
          {/* header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '15px 18px', borderBottom: '1px solid rgba(255,255,255,0.08)', background: 'linear-gradient(180deg, rgba(242,59,254,0.08), transparent)' }}>
            <span style={{ position: 'relative', width: 38, height: 38, borderRadius: 999, background: GRAD, display: 'grid', placeItems: 'center' }}>
              <Icon n="Sparkles" s={18} color="#08080A" />
              <span style={{ position: 'absolute', right: -1, bottom: -1, width: 11, height: 11, borderRadius: 999, background: '#2DE3A0', border: '2px solid #0C0C0F' }} />
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>Winkz Assistant</div>
              <div style={{ fontSize: 11, color: '#2DE3A0', fontFamily: 'var(--font-mono)', display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 5, height: 5, borderRadius: 999, background: '#2DE3A0' }} />online · replies instantly</div>
            </div>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: '#667', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 999, padding: '3px 7px' }}>AI</span>
          </div>

          {/* body */}
          <div ref={bodyRef} style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 6px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {msgs.map((m, i) => (
              <div key={i} style={{ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start', maxWidth: '85%', fontSize: 13.5, lineHeight: 1.5, padding: '10px 13px', borderRadius: 14, borderBottomRightRadius: m.role === 'user' ? 4 : 14, borderBottomLeftRadius: m.role === 'user' ? 14 : 4, background: m.role === 'user' ? 'rgba(121,186,255,0.16)' : 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.07)', color: m.role === 'user' ? '#dfeaff' : '#e7eaf2' }}>{m.content}</div>
            ))}
            {busy && (
              <div style={{ alignSelf: 'flex-start', display: 'flex', gap: 4, padding: '11px 14px', borderRadius: 14, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.07)' }}>
                {[0, 1, 2].map(d => <span key={d} style={{ width: 6, height: 6, borderRadius: 999, background: '#889', animation: `wz-typ 1s ${d * 0.15}s infinite` }} />)}
              </div>
            )}
            {chips.length > 0 && !busy && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 2 }}>
                {chips.map((s, i) => (
                  <button key={i} onClick={() => send(s === 'Book a call' || s === 'Contact' ? 'book a call' : s === 'See your work' ? 'portfolio' : s)} style={{ cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--winkz-blue)', background: 'rgba(121,186,255,0.07)', border: '1px solid rgba(121,186,255,0.3)', borderRadius: 999, padding: '7px 12px' }}>{s}</button>
                ))}
              </div>
            )}
            {msgs.length <= 1 && !busy && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 4 }}>
                {SUGGEST.map((s, i) => (
                  <button key={i} onClick={() => send(s)} style={{ cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--winkz-cyan)', background: 'rgba(45,227,234,0.06)', border: '1px solid rgba(45,227,234,0.28)', borderRadius: 999, padding: '7px 12px' }}>{s}</button>
                ))}
              </div>
            )}
          </div>

          {/* input */}
          <div style={{ padding: 12, borderTop: '1px solid rgba(255,255,255,0.08)', display: 'flex', gap: 8 }}>
            <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') send(); }} placeholder="Ask anything…" style={{ flex: 1, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 11, padding: '11px 14px', color: 'var(--text-primary)', fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none' }} />
            <button onClick={() => send()} disabled={busy || !input.trim()} style={{ width: 44, borderRadius: 11, border: 'none', cursor: busy || !input.trim() ? 'default' : 'pointer', background: busy || !input.trim() ? 'rgba(255,255,255,0.08)' : GRAD, display: 'grid', placeItems: 'center', transition: 'background .2s' }}><Icon n="Send" s={17} color={busy || !input.trim() ? '#667' : '#08080A'} /></button>
          </div>
        </div>
        <style>{`@keyframes wz-typ{0%,60%,100%{opacity:.3;transform:translateY(0)}30%{opacity:1;transform:translateY(-3px)}}`}</style>
      </React.Fragment>
    );
  }

  window.ChatWidget = ChatWidget;
})();
