/* ============================================================
       MSH PI, INC. — AI Chatbot  (Standalone HTML embed)
       Source: mshpi-chatbot.jsx  (same logic, inlined here)
       ============================================================ */

    const { useState, useEffect, useRef } = React;

    // ── Config ──────────────────────────────────────────────────
    const CHATBOT_PROXY = "/chatbot-proxy/";
    const LOGO_URL = "/assets/MSHPI_CHAT_ICON.svg";
    const CF_ENDPOINTS = [
      CHATBOT_PROXY,
      "/chatbot-proxy/index.php",
      "https://mshpi-ai-proxy.jhan1102.workers.dev",
      "https://mshpi-ai-proxy.jhan1102.workers.dev/"
    ];

    // SYSTEM_PROMPT is stored securely in the Cloudflare Worker — not exposed here.

    const PHONE_EN =
      "📞 LA Office: (213) 383-7007\n" +
      "📞 English 24hrs: (213) 784-2522\n" +
      "📞 한국어 24시간: (323) 633-3232";
    const ERR_MSG = "⚠️ Unable to connect. Please call us directly:\n" + PHONE_EN;

    const DEFAULT_COLORS = {
      headerBg: "#0f1e35", headerText: "#c9a84c",
      bubbleBg: "#0f1e35", bubbleIcon: "#c9a84c",
      userBubble: "#4E82EE", botBubble: "#f0f4f8",
      chatBg: "#ffffff", sendBtn: "#4E82EE", accentColor: "#c9a84c",
    };

    const QUICK = [
      { label: "Our Services",  msg: "What services do you offer?" },
      { label: "Contact Us",    msg: "How do I contact MSH PI?" },
      { label: "Consultation",  msg: "I would like a consultation." },
      { label: "서비스 안내",   msg: "어떤 서비스를 제공하시나요?" },
      { label: "연락처",         msg: "어떻게 연락하나요?" },
    ];

    async function callWorker(messages) {
      let lastErr;
      for (const endpoint of CF_ENDPOINTS) {
        try {
          const r = await fetch(endpoint, {
            method: "POST",
            credentials: "omit",
            headers: { "Content-Type": "application/json", "Accept": "application/json, text/plain;q=0.9, */*;q=0.8" },
            body: JSON.stringify({ messages, site: "mshpi", source: "website" }),
          });
          if (!r.ok) throw new Error(`cf_fail_${r.status}_${endpoint}`);
          const contentType = (r.headers.get("content-type") || "").toLowerCase();
          if (contentType.includes("application/json")) {
            const d = await r.json();
            if (d?.text) return d.text;
            if (typeof d?.reply === "string" && d.reply.trim()) return d.reply;
            if (typeof d?.message === "string" && d.message.trim()) return d.message;
          } else {
            const t = (await r.text()).trim();
            if (t) return t;
          }
          throw new Error("no_text");
        } catch (err) {
          lastErr = err;
        }
      }
      throw lastErr || new Error("cf_fail");
    }

    function Bubble({ role, text, colors }) {
      const isBot = role === "bot";
      const lines = text.split("\n");
      return (
        <div style={{ display:"flex", gap:8, flexDirection:isBot?"row":"row-reverse", animation:"mshin 0.25s ease" }}>
          <div style={{ width:32,height:32,borderRadius:8,flexShrink:0,marginTop:2,
            background:isBot?colors.bubbleBg:"rgba(0,0,0,0.07)",
            display:"flex",alignItems:"center",justifyContent:"center" }}>
            {isBot
              ? <span style={{ color:colors.bubbleIcon,fontWeight:900,fontSize:15,letterSpacing:"-0.5px",lineHeight:1,fontFamily:"system-ui,sans-serif" }}>M</span>
              : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(0,0,0,0.38)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                </svg>
            }
          </div>
          <div style={{ maxWidth:"82%",padding:"10px 13px",
            background:isBot?colors.botBubble:colors.userBubble,
            border:"1px solid "+(isBot?"rgba(0,0,0,0.07)":"rgba(255,255,255,0.1)"),
            borderRadius:isBot?"3px 12px 12px 12px":"12px 3px 12px 12px",
            boxShadow:"0 1px 3px rgba(0,0,0,0.06)" }}>
            {lines.map((line,i) => {
              const isDisclaimer = line.includes("Many Korean Private Investigation agencies") || line.includes("MSH PI, INC. has been operating for more than 21 years") || line.includes("FOR INVESTIGATIVE SERVICES");
              const isBold = !isDisclaimer && line.startsWith("**") && line.endsWith("**");
              const clean = line.replace(/[*][*]([^*]+)[*][*]/g,"$1").replace(/[*]([^*]+)[*]/g,"$1");
              if (!clean.trim()) return <div key={i} style={{height:4}}/>;
              const warn = clean.startsWith("⚠️");
              return (
                <div key={i} style={{ fontSize:13,lineHeight:1.75,marginBottom:1,
                  color:warn?"#b45309":(isBot?"#1a1a2e":"#fff"),
                  fontWeight:warn?500:(isBold?700:(isBot&&i===0&&!warn?600:400)) }}>
                  {clean.split(/(https?:\/\/\S+|\(\d{3}\)\s?\d{3}[-\s\.]\d{4}|\b\d{3}[-\.]\d{3}[-\.]\d{4}\b)/g).map((part,j) => {
                    if (part.match(/^https?:\/\//)) return <a key={j} href={part} target="_blank" rel="noopener noreferrer" style={{color:"#E24A31",textDecoration:"underline"}}>{part} ↗</a>;
                    if (part.match(/^(?:\(\d{3}\)|\d{3}[-\.])/)) return <a key={j} href={"tel:+1"+part.replace(/\D/g,"")} style={{color:"#E24A31",textDecoration:"underline",fontWeight:600}}>{part}</a>;
                    return <span key={j}>{part}</span>;
                  })}
                </div>
              );
            })}
          </div>
        </div>
      );
    }

    function AdminPanel({ colors, onSave, onClose }) {
      const [local,setLocal]=useState({...colors});
      const set=(k,v)=>{const n={...local,[k]:v};setLocal(n);onSave(n);};
      const FIELDS=[["Header BG","headerBg"],["Header Text","headerText"],["Bubble BG","bubbleBg"],["Bubble Icon","bubbleIcon"],["User Msg BG","userBubble"],["Bot Msg BG","botBubble"],["Window BG","chatBg"],["Send Button","sendBtn"],["Accent","accentColor"]];
      return (
        <div onClick={onClose} style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center"}}>
          <div onClick={e=>e.stopPropagation()} style={{background:"#fff",borderRadius:14,padding:22,width:300,maxHeight:"85vh",overflowY:"auto",boxShadow:"0 16px 48px rgba(0,0,0,0.3)"}}>
            <div style={{fontSize:15,fontWeight:700,color:"#0f1e35",marginBottom:14}}>🔧 Colour Settings</div>
            {FIELDS.map(([label,key])=>(
              <div key={key} style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
                <span style={{fontSize:12,color:"#444"}}>{label}</span>
                <div style={{display:"flex",gap:6,alignItems:"center"}}>
                  <input type="color" value={local[key]} onChange={e=>set(key,e.target.value)} style={{width:32,height:24,border:"1px solid #ddd",borderRadius:4,cursor:"pointer",padding:2}}/>
                  <span style={{fontSize:10,color:"#888",fontFamily:"monospace",minWidth:52}}>{local[key]}</span>
                </div>
              </div>
            ))}
            <button onClick={()=>{setLocal(DEFAULT_COLORS);onSave(DEFAULT_COLORS);}} style={{width:"100%",marginTop:8,padding:7,background:"#f3f4f6",border:"1px solid #ddd",borderRadius:8,fontSize:12,cursor:"pointer"}}>Reset Defaults</button>
            <button onClick={onClose} style={{width:"100%",marginTop:10,padding:7,background:"#f3f4f6",border:"1px solid #ddd",borderRadius:8,fontSize:12,cursor:"pointer"}}>Close</button>
          </div>
        </div>
      );
    }

    function MSHPIChatbot() {
      const [msgs,setMsgs]=useState([]); const [hist,setHist]=useState([]); const [input,setInput]=useState("");
      const [busy,setBusy]=useState(false); const [quick,setQuick]=useState(true); const [open,setOpen]=useState(()=>{ try { return localStorage.getItem("mshpi_chat_open") !== "0"; } catch { return true; } });
      const [admin,setAdmin]=useState(false); const [colors,setColors]=useState(DEFAULT_COLORS);
      const bottomRef=useRef(null); const inputRef=useRef(null); const taRef=useRef(null);

      useEffect(()=>{
        setTimeout(()=>{
          setMsgs([{id:1,role:"bot",text:"**안녕하세요! MSH PI, INC.에 연락해 주셔서 감사합니다.**\n**오늘 어떻게 도와드릴까요?**\n🇰🇷 웹사이트를 한국어로 보려면 메뉴에서 한국 국기를 선택하세요.\n\n**Hello! Thank you for contacting MSH PI, INC.**\n**How can I help you today?**"}]);
        },300);
      },[]);

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

      const saveColors=c=>{ setColors(c); try{localStorage.setItem("mshpi_colors",JSON.stringify(c));}catch{} };

      useEffect(()=>{ try{const s=localStorage.getItem("mshpi_colors");if(s)setColors(JSON.parse(s));}catch{} },[]);
      useEffect(()=>{ try{localStorage.setItem("mshpi_chat_open", open ? "1" : "0");}catch{} },[open]);

      const send=async text=>{
        const t=(text||"").trim(); if(!t||busy)return;
        setInput(""); if(taRef.current)taRef.current.style.height="";
        setQuick(false); setBusy(true);
        setMsgs(prev=>[...prev,{id:Date.now(),role:"user",text:t}]);
        const newHist=[...hist,{role:"user",content:t}];
        const isKorean=/[\uAC00-\uD7A3\u1100-\u11FF\u3130-\u318F]/.test(t);
        const langHint=isKorean?"[Reply ONLY in Korean] ":"[Reply ONLY in English] ";
        const apiHist=newHist.map((m,i)=>i===newHist.length-1&&m.role==="user"?{...m,content:langHint+m.content}:m);
        let reply;
        try { reply=await callWorker(apiHist); } catch(e) { reply=null; }
        let botText=reply||ERR_MSG;
        botText=botText.replace(/https?:\/\/(?:www\.)?mshpiinc\.com[^\s)]*/gi,"");
        botText=botText.replace(/\*{0,2}MSH PI,? INC?\.? has been operating for more than 21[\s\S]*?outside firms\.(?:[^\n]*)?\*{0,2}\n?/gi,"")
                       .replace(/\*{0,2}Many Korean Private Investigation[\s\S]*?outside firms\.(?:[^\n]*)?\*{0,2}\n?/gi,"")
                       .replace(/\n{3,}/g,"\n\n").trim();
        if(/contact\s+page/i.test(botText)&&!botText.includes("mshpi.com/contact")){
          const kr=/[\uAC00-\uD7A3]/.test(botText);
          botText+=kr?"\nhttps://www.mshpi.com/ko/contact-korean-private-investigator":"\nhttps://www.mshpi.com/contact-korean-private-investigator";
        }
        if(!botText.trim()) botText=ERR_MSG;
        setHist([...newHist,{role:"assistant",content:botText}]);
        setMsgs(prev=>[...prev,{id:Date.now()+1,role:"bot",text:botText}]);
        setBusy(false);
        setTimeout(()=>inputRef.current?.focus(),50);
      };

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

      if(!open) return (
        <div style={{position:"fixed",bottom:24,right:24,zIndex:9998}}>
          <button onClick={()=>setOpen(true)} style={{width:92,height:92,borderRadius:"50%",border:"4px solid #586274",background:"#ffffff",boxShadow:"0 10px 30px rgba(0,0,0,0.28)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"visible",padding:0}}>
            <img src={LOGO_URL} style={{width:68,height:68,objectFit:"contain",display:"block"}}
              onError={e=>{e.target.style.display="none";e.target.parentNode.insertAdjacentHTML("afterbegin",`<span style="color:${colors.bubbleIcon};font-size:20px;font-weight:800">M</span>`);}}/>
            <div style={{position:"absolute",top:-1,right:-1,width:22,height:22,borderRadius:"50%",background:"#22c55e",border:"3px solid #fff",boxSizing:"border-box",zIndex:2}}/>
          </button>
        </div>
      );

      return (
        <div style={{position:"fixed",bottom:24,right:24,zIndex:9998,fontFamily:"'Segoe UI',system-ui,sans-serif"}}>
          {admin&&<AdminPanel colors={colors} onSave={saveColors} onClose={()=>setAdmin(false)}/>}
          <div style={{width:460,maxWidth:"calc(100vw - 48px)",background:colors.chatBg,border:"1px solid rgba(0,0,0,0.1)",borderRadius:18,boxShadow:"0 8px 40px rgba(0,0,0,0.15)",display:"flex",flexDirection:"column",height:"min(700px,94vh)",overflow:"hidden"}}>

            {/* Header */}
            <div style={{background:colors.headerBg,padding:"12px 14px",borderBottom:"1px solid rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:10,flexShrink:0}}>
              <div style={{width:64,height:64,borderRadius:16,background:"#ffffff",flexShrink:0,border:"1.5px solid rgba(255,255,255,0.25)",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",overflow:"hidden"}}>
                <img src={LOGO_URL}
                  style={{width:50,height:50,objectFit:"contain",display:"block"}}
                  onError={e=>{e.target.style.display="none";e.target.parentNode.innerHTML='<span style="color:#c9a84c;font-weight:900;font-size:24px">M</span>';}}
                />
              </div>
              <div style={{flex:1}}>
                <div style={{fontFamily:"system-ui,sans-serif",fontSize:15,fontWeight:800,color:"#ffffff"}}>MSH PI, INC.</div>
                <div style={{display:"flex",alignItems:"center",gap:5,marginTop:2}}>
                  <div style={{width:6,height:6,borderRadius:"50%",background:busy?"#f59e0b":"#22c55e"}}/>
                  <span style={{fontSize:11,color:"rgba(255,255,255,0.5)"}}>{busy?"Thinking...":"Online"} · 한국어 가능</span>
                </div>
              </div>
              
              <button onClick={()=>setOpen(false)} title="Close"
                style={{width:30,height:30,borderRadius:6,border:"none",cursor:"pointer",background:"rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.75)",fontSize:18,display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,transition:"background 0.15s,color 0.15s"}}
                onMouseEnter={e=>{e.currentTarget.style.background="rgba(220,50,50,0.75)";e.currentTarget.style.color="#fff";}}
                onMouseLeave={e=>{e.currentTarget.style.background="rgba(255,255,255,0.1)";e.currentTarget.style.color="rgba(255,255,255,0.75)";}}>✕</button>
            </div>

            {/* Licence bar */}
            <div style={{background:"#e8edf3",borderBottom:"1px solid rgba(0,0,0,0.1)",padding:"4px 16px",display:"flex",alignItems:"center",flexShrink:0}}>
              <span style={{fontSize:10.5,color:"#1f2937"}}>
                <span style={{color:colors.accentColor,fontWeight:700}}>CA PI Lic #24994</span>{" · "}Est. 2004 · Licensed & Insured
              </span>
            </div>

            {/* Messages */}
            <div style={{flex:1,overflowY:"auto",padding:"16px 12px",display:"flex",flexDirection:"column",gap:12,background:colors.chatBg}}>
              {msgs.map(m=><Bubble key={m.id} role={m.role} text={m.text} colors={colors}/>)}
              {busy&&(
                <div style={{display:"flex",gap:8}}>
                  <div style={{width:32,height:32,borderRadius:8,flexShrink:0,background:colors.bubbleBg,display:"flex",alignItems:"center",justifyContent:"center"}}>
                    <span style={{color:colors.bubbleIcon,fontWeight:900,fontSize:15,lineHeight:1,fontFamily:"system-ui,sans-serif"}}>M</span>
                  </div>
                  <div style={{padding:"12px 14px",background:colors.botBubble,border:"1px solid rgba(0,0,0,0.07)",borderRadius:"3px 12px 12px 12px"}}>
                    <div style={{display:"flex",gap:5}}>
                      {[0,1,2].map(i=><div key={i} style={{width:7,height:7,borderRadius:"50%",background:colors.accentColor,animation:`mshbounce 1.2s infinite ${i*0.2}s`}}/>)}
                    </div>
                  </div>
                </div>
              )}
              <div ref={bottomRef}/>
            </div>

            {/* Quick replies */}
            {quick&&(
              <div style={{display:"flex",flexWrap:"wrap",gap:6,padding:"0 12px 10px",background:colors.chatBg,flexShrink:0}}>
                {QUICK.map(q=>(
                  <button key={q.msg} onClick={()=>send(q.msg)} disabled={busy}
                    style={{background:"transparent",border:`1px solid ${colors.accentColor}55`,borderRadius:20,padding:"5px 12px",color:colors.accentColor,fontSize:11.5,cursor:busy?"not-allowed":"pointer",whiteSpace:"nowrap",opacity:busy?0.5:1}}>
                    {q.label}
                  </button>
                ))}
              </div>
            )}

            {/* Input */}
            <div style={{background:"#f8f9fa",borderTop:"1px solid rgba(0,0,0,0.08)",padding:"10px 12px 12px",flexShrink:0}}>
              <div style={{display:"flex",gap:8,alignItems:"flex-end"}}>
                <textarea ref={el=>{inputRef.current=el;taRef.current=el;}} value={input} rows={1} disabled={busy}
                  placeholder="Type your question... / 질문을 입력하세요..."
                  onChange={e=>{setInput(e.target.value);e.target.style.height="auto";e.target.style.height=Math.min(e.target.scrollHeight,96)+"px";}}
                  onKeyDown={onKey}
                  onFocus={e=>e.target.style.borderColor=colors.accentColor}
                  onBlur={e=>e.target.style.borderColor="rgba(0,0,0,0.12)"}
                  style={{flex:1,background:"#fff",border:"1px solid rgba(0,0,0,0.12)",borderRadius:10,color:"#1a1a2e",fontFamily:"inherit",fontSize:13.5,padding:"9px 12px",resize:"none",outline:"none",maxHeight:96,lineHeight:1.5,opacity:busy?0.6:1}}/>
                <button onClick={()=>send(input)} disabled={!input.trim()||busy}
                  style={{width:52,height:52,borderRadius:10,border:"none",flexShrink:0,background:(!input.trim()||busy)?colors.accentColor+"33":colors.sendBtn,display:"flex",alignItems:"center",justifyContent:"center",cursor:(!input.trim()||busy)?"not-allowed":"pointer"}}>
                  {busy
                    ?<div style={{width:14,height:14,borderRadius:"50%",border:"2px solid rgba(255,255,255,0.3)",borderTopColor:"#fff",animation:"mshspin 0.8s linear infinite"}}/>
                    :<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={!input.trim()?"rgba(0,0,0,0.2)":"#fff"} strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                  }
                </button>
              </div>
              <div style={{fontSize:10,color:"#9ca3af",textAlign:"center",marginTop:6}}>
                Do not submit sensitive information unless authorised. Submission is at your own risk.{" "}
                <a href="https://www.mshpi.com/privacy-policy" target="_blank" rel="noopener noreferrer" style={{color:"#E24A31"}}>Privacy Policy</a>.
              </div>
            </div>
          </div>

          <style>{`
            @keyframes mshin     { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:none} }
            @keyframes mshbounce { 0%,80%,100%{transform:translateY(0);opacity:.3} 40%{transform:translateY(-5px);opacity:1} }
            @keyframes mshspin   { to{transform:rotate(360deg)} }
            textarea::placeholder { color:#9ca3af }
            ::-webkit-scrollbar { width:4px }
            ::-webkit-scrollbar-thumb { background:rgba(0,0,0,.1);border-radius:2px }
          `}</style>
        </div>
      );
    }

    const root = ReactDOM.createRoot(document.getElementById("mshpi-chatbot-root"));
    root.render(<MSHPIChatbot />);