UNPKG

@forbespro/lead-agent

Version:
85 lines (77 loc) 38.1 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),n=require("react"),v=require("./index5.js"),G=require("./index6.js"),ke=require("./index7.js"),De=require("./index8.js"),Fe=require("./index9.js"),ve=require("./index10.js"),Ue=require("./index11.js"),ae=require("./index12.js"),Ge=require("./index13.js"),He=require("./index14.js"),te=[{label:"Accounting",value:"ACCOUNTING"},{label:"Airlines/Aviation",value:"AIRLINES_AVIATION"},{label:"Alternative Dispute Resolution",value:"ALTERNATIVE_DISPUTE_RESOLUTION"},{label:"Alternative Medicine",value:"ALTERNATIVE_MEDICINE"},{label:"Animation",value:"ANIMATION"},{label:"Apparel & Fashion",value:"APPAREL_FASHION"},{label:"Architecture & Planning",value:"ARCHITECTURE_PLANNING"},{label:"Arts and Crafts",value:"ARTS_AND_CRAFTS"},{label:"Automotive",value:"AUTOMOTIVE"},{label:"Aviation & Aerospace",value:"AVIATION_AEROSPACE"},{label:"Banking",value:"BANKING"},{label:"Biotechnology",value:"BIOTECHNOLOGY"},{label:"Broadcast Media",value:"BROADCAST_MEDIA"},{label:"Building Materials",value:"BUILDING_MATERIALS"},{label:"Business Supplies and Equipment",value:"BUSINESS_SUPPLIES_AND_EQUIPMENT"},{label:"Capital Markets",value:"CAPITAL_MARKETS"},{label:"Chemicals",value:"CHEMICALS"},{label:"Civic & Social Organization",value:"CIVIC_SOCIAL_ORGANIZATION"},{label:"Civil Engineering",value:"CIVIL_ENGINEERING"},{label:"Commercial Real Estate",value:"COMMERCIAL_REAL_ESTATE"},{label:"Computer & Network Security",value:"COMPUTER_NETWORK_SECURITY"},{label:"Computer Games",value:"COMPUTER_GAMES"},{label:"Computer Hardware",value:"COMPUTER_HARDWARE"},{label:"Computer Networking",value:"COMPUTER_NETWORKING"},{label:"Computer Software",value:"COMPUTER_SOFTWARE"},{label:"Construction",value:"CONSTRUCTION"},{label:"Consumer Electronics",value:"CONSUMER_ELECTRONICS"},{label:"Consumer Goods",value:"CONSUMER_GOODS"},{label:"Consumer Services",value:"CONSUMER_SERVICES"},{label:"Corporate Solutions",value:"Corporate Solutions"},{label:"Cosmetics",value:"COSMETICS"},{label:"Dairy",value:"DAIRY"},{label:"Defense & Space",value:"DEFENSE_SPACE"},{label:"Design",value:"DESIGN"},{label:"E-Learning",value:"E_LEARNING"},{label:"Education Management",value:"EDUCATION_MANAGEMENT"},{label:"Electrical/Electronic Manufacturing",value:"ELECTRICAL_ELECTRONIC_MANUFACTURING"},{label:"Emergency Services",value:"Emergency Services"},{label:"Entertainment",value:"ENTERTAINMENT"},{label:"Environmental Services",value:"ENVIRONMENTAL_SERVICES"},{label:"Equestrian and Animal Centres",value:"Equestrian and Animal Centres"},{label:"Events Services",value:"EVENTS_SERVICES"},{label:"Executive Office",value:"EXECUTIVE_OFFICE"},{label:"Facilities Services",value:"FACILITIES_SERVICES"},{label:"Farming",value:"FARMING"},{label:"Financial Services",value:"FINANCIAL_SERVICES"},{label:"Fine Art",value:"FINE_ART"},{label:"Fishery",value:"FISHERY"},{label:"Food & Beverages",value:"FOOD_BEVERAGES"},{label:"Fund-Raising",value:"FUND_RAISING"},{label:"Furniture",value:"FURNITURE"},{label:"Gambling & Casinos",value:"GAMBLING_CASINOS"},{label:"Glass, Ceramics & Concrete",value:"GLASS_CERAMICS_CONCRETE"},{label:"Government Administration",value:"GOVERNMENT_ADMINISTRATION"},{label:"Government Relations",value:"GOVERNMENT_RELATIONS"},{label:"Graphic Design",value:"GRAPHIC_DESIGN"},{label:"Hair & Beauty Salons",value:"Hair & Beauty Salons"},{label:"Health, Wellness and Fitness",value:"HEALTH_WELLNESS_AND_FITNESS"},{label:"Higher Education",value:"HIGHER_EDUCATION"},{label:"Holiday & Caravan Parks",value:"Holiday & Caravan Parks"},{label:"Holiday Cottages",value:"Holiday Cottages"},{label:"Hospital & Health Care",value:"HOSPITAL_HEALTH_CARE"},{label:"Hospitality",value:"HOSPITALITY"},{label:"Housing Associations",value:"Housing Associations"},{label:"Human Resources",value:"HUMAN_RESOURCES"},{label:"Import and Export",value:"IMPORT_AND_EXPORT"},{label:"Individual & Family Services",value:"INDIVIDUAL_FAMILY_SERVICES"},{label:"Industrial Automation",value:"INDUSTRIAL_AUTOMATION"},{label:"Information Services",value:"INFORMATION_SERVICES"},{label:"Information Technology and Services",value:"INFORMATION_TECHNOLOGY_AND_SERVICES"},{label:"Insurance",value:"INSURANCE"},{label:"International Affairs",value:"INTERNATIONAL_AFFAIRS"},{label:"International Trade and Development",value:"INTERNATIONAL_TRADE_AND_DEVELOPMENT"},{label:"Internet",value:"INTERNET"},{label:"Investment Banking",value:"INVESTMENT_BANKING"},{label:"Investment Management",value:"INVESTMENT_MANAGEMENT"},{label:"Judiciary",value:"JUDICIARY"},{label:"Landlords",value:"Landlords"},{label:"Launderettes & Dry Cleaners",value:"Launderettes & Dry Cleaners"},{label:"Law Enforcement",value:"LAW_ENFORCEMENT"},{label:"Law Practice",value:"LAW_PRACTICE"},{label:"Legal Services",value:"LEGAL_SERVICES"},{label:"Legeislative Office",value:"LEGISLATIVE_OFFICE"},{label:"Leisure Centres, Gyms and Spas",value:"Leisure Centres, Gyms and Spas"},{label:"Leisure, Travel & Tourism",value:"LEISURE_TRAVEL_TOURISM"},{label:"Libraries",value:"LIBRARIES"},{label:"Logistics and Supply Chain",value:"LOGISTICS_AND_SUPPLY_CHAIN"},{label:"Luxury Goods & Jewelry",value:"LUXURY_GOODS_JEWELRY"},{label:"Machinery",value:"MACHINERY"},{label:"Management Consulting",value:"MANAGEMENT_CONSULTING"},{label:"Marine & Offshore",value:"Marine & Offshore"},{label:"Maritime",value:"MARITIME"},{label:"Market Research",value:"MARKET_RESEARCH"},{label:"Marketing and Advertising",value:"MARKETING_AND_ADVERTISING"},{label:"Mechanical or Industrial Engineering",value:"MECHANICAL_OR_INDUSTRIAL_ENGINEERING"},{label:"Media Production",value:"MEDIA_PRODUCTION"},{label:"Medical Devices",value:"MEDICAL_DEVICES"},{label:"Medical Practice",value:"MEDICAL_PRACTICE"},{label:"Mental Health Care",value:"MENTAL_HEALTH_CARE"},{label:"Military",value:"MILITARY"},{label:"Mining & Metals",value:"MINING_METALS"},{label:"Ministry of Defence",value:"Ministry of Defence"},{label:"Motion Pictures and Film",value:"MOTION_PICTURES_AND_FILM"},{label:"Museums and Institutions",value:"MUSEUMS_AND_INSTITUTIONS"},{label:"Music",value:"MUSIC"},{label:"Nanotechnology",value:"NANOTECHNOLOGY"},{label:"Newspapers",value:"NEWSPAPERS"},{label:"Non-Profit Organization Management",value:"NON_PROFIT_ORGANIZATION_MANAGEMENT"},{label:"Nursing & Care",value:"Nursing & Care"},{label:"Oil & Energy",value:"OIL_ENERGY"},{label:"Online Media",value:"ONLINE_MEDIA"},{label:"Outsourcing/Offshoring",value:"OUTSOURCING_OFFSHORING"},{label:"Package/Freight Delivery",value:"PACKAGE_FREIGHT_DELIVERY"},{label:"Packaging and Containers",value:"PACKAGING_AND_CONTAINERS"},{label:"Paper & Forest Products",value:"PAPER_FOREST_PRODUCTS"},{label:"PBSA",value:"PBSA"},{label:"Performing Arts",value:"PERFORMING_ARTS"},{label:"Pharmaceuticals",value:"PHARMACEUTICALS"},{label:"Philanthropy",value:"PHILANTHROPY"},{label:"Photography",value:"PHOTOGRAPHY"},{label:"Plastics",value:"PLASTICS"},{label:"Political Organization",value:"POLITICAL_ORGANIZATION"},{label:"Primary/Secondary Education",value:"PRIMARY_SECONDARY_EDUCATION"},{label:"Printing",value:"PRINTING"},{label:"Professional Training & Coaching",value:"PROFESSIONAL_TRAINING_COACHING"},{label:"Program Development",value:"PROGRAM_DEVELOPMENT"},{label:"Public Policy",value:"PUBLIC_POLICY"},{label:"Public Relations and Communications",value:"PUBLIC_RELATIONS_AND_COMMUNICATIONS"},{label:"Public Safety",value:"PUBLIC_SAFETY"},{label:"Publishing",value:"PUBLISHING"},{label:"Railroad Manufacture",value:"RAILROAD_MANUFACTURE"},{label:"Ranching",value:"RANCHING"},{label:"Real Estate",value:"REAL_ESTATE"},{label:"Recreational Facilities and Services",value:"RECREATIONAL_FACILITIES_AND_SERVICES"},{label:"Religious Institutions",value:"RELIGIOUS_INSTITUTIONS"},{label:"Renewables & Environment",value:"RENEWABLES_ENVIRONMENT"},{label:"Research",value:"RESEARCH"},{label:"Restaurants",value:"RESTAURANTS"},{label:"Retail",value:"Retail"},{label:"Security and Investigations",value:"SECURITY_AND_INVESTIGATIONS"},{label:"Semiconductors",value:"SEMICONDUCTORS"},{label:"Serviced Apartments",value:"Serviced Apartments"},{label:"Shipbuilding",value:"SHIPBUILDING"},{label:"Sporting Goods",value:"SPORTING_GOODS"},{label:"Sports",value:"SPORTS"},{label:"Staffing and Recruiting",value:"STAFFING_AND_RECRUITING"},{label:"Student Apartments",value:"Student Apartments"},{label:"Supermarkets",value:"SUPERMARKETS"},{label:"Telecommunications",value:"TELECOMMUNICATIONS"},{label:"Textiles",value:"TEXTILES"},{label:"Think Tanks",value:"THINK_TANKS"},{label:"Tobacco",value:"TOBACCO"},{label:"Translation and Localization",value:"TRANSLATION_AND_LOCALIZATION"},{label:"Transportation/Trucking/Railroad",value:"TRANSPORTATION_TRUCKING_RAILROAD"},{label:"Utilities",value:"UTILITIES"},{label:"Venture Capital & Private Equity",value:"VENTURE_CAPITAL_PRIVATE_EQUITY"},{label:"Veterinary",value:"VETERINARY"},{label:"Warehousing",value:"WAREHOUSING"},{label:"Wholesale",value:"WHOLESALE"},{label:"Wine and Spirits",value:"WINE_AND_SPIRITS"},{label:"Wireless",value:"WIRELESS"},{label:"Writing and Editing",value:"WRITING_AND_EDITING"}],Ne=()=>e.jsxs("div",{className:"fpl-flex fpl-items-center fpl-justify-center fpl-w-6 fpl-h-6 fpl-relative",children:[e.jsx("style",{children:` @keyframes orbitAnimation { 0% { transform: rotate(0deg) translateX(4px) rotate(0deg); } 100% { transform: rotate(360deg) translateX(4px) rotate(-360deg); } } .orb { position: absolute; width: 5px; height: 5px; border-radius: 50%; background-color: white; animation: orbitAnimation 1.5s infinite linear; } .orb:nth-child(1) { animation-delay: 0s; opacity: 0.95; } .orb:nth-child(2) { animation-delay: -0.5s; opacity: 0.85; } .orb:nth-child(3) { animation-delay: -1s; opacity: 0.75; } `}),e.jsx("div",{className:"orb"}),e.jsx("div",{className:"orb"}),e.jsx("div",{className:"orb"})]}),qe=({options:b,placeholder:o,onSelect:i,id:p,value:I,onChange:P})=>{const[r,m]=n.useState(!1),y=b.filter(c=>c.toLowerCase().includes(I.toLowerCase())).slice(0,10);return e.jsxs("div",{className:"fpl-relative fpl-w-full",children:[e.jsx(G.Input,{id:p,value:I,onChange:c=>{P(c.target.value),m(!0)},onFocus:()=>m(!0),placeholder:o,className:"fpl-w-full"}),r&&y.length>0&&e.jsx("div",{className:"fpl-absolute fpl-z-10 fpl-mt-1 fpl-w-full fpl-bg-white fpl-shadow-lg fpl-max-h-60 fpl-rounded-md fpl-py-1 fpl-text-base fpl-overflow-auto",children:y.map((c,W)=>e.jsx("div",{onClick:()=>{i(c),P(c),m(!1)},className:"fpl-cursor-pointer fpl-select-none fpl-relative fpl-py-2 fpl-pl-3 fpl-pr-9 hover:fpl-bg-gray-100",children:c},W))})]})},Be=()=>e.jsxs("div",{className:"fpl-flex fpl-items-center fpl-gap-3 fpl-bg-gray-100 fpl-text-gray-700 fpl-rounded-lg fpl-p-3.5 fpl-rounded-bl-none fpl-max-w-[275px] fpl-shadow-sm",role:"status","aria-live":"polite",children:[e.jsx("div",{className:"fpl-text-sm fpl-font-medium",children:"Thinking"}),e.jsx("div",{className:"fpl-flex fpl-items-center fpl-space-x-1.5",children:e.jsxs("div",{className:"thinking-dots-container",children:[e.jsx("style",{children:` @keyframes pulse { 0%, 100% { transform: scale(0.8); opacity: 0.6; } 50% { transform: scale(1.2); opacity: 1; } } @media (prefers-reduced-motion: reduce) { .thinking-dot { animation: none !important; opacity: 0.8; } } .thinking-dot { height: 0.5rem; width: 0.5rem; border-radius: 50%; background: linear-gradient(135deg, #6366f1, #8b5cf6); animation: pulse 1.5s ease-in-out infinite; box-shadow: 0 0 4px rgba(99, 102, 241, 0.3); } .thinking-dots-container { display: flex; align-items: center; gap: 4px; } `}),e.jsx("div",{className:"thinking-dot",style:{animationDelay:"0ms"},"aria-hidden":"true"}),e.jsx("div",{className:"thinking-dot",style:{animationDelay:"200ms"},"aria-hidden":"true"}),e.jsx("div",{className:"thinking-dot",style:{animationDelay:"400ms"},"aria-hidden":"true"})]})}),e.jsx("span",{className:"fpl-sr-only",children:"Assistant is thinking, please wait"})]}),C=(b,o,i)=>{b(o,i)},Ve=async b=>{if(!b.email||!b.name||!b.phone)return null;try{const o=localStorage.getItem("chatId");if(!o)return console.error("No chat ID found in localStorage"),null;const i=await fetch("/api/hubspot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chatId:o,userData:b})});if(!i.ok)throw new Error(`Failed to create HubSpot contact: ${i.statusText}`);const p=await i.json();return p.hubspotId,p.hubspotId}catch(o){return console.error("Error creating HubSpot contact:",o),null}},Ie=(b,o)=>{let i="",p="";return o.toLowerCase().includes("your name")?(i="Full Name",p="Enter your full name"):o.toLowerCase().includes("email")?(i="Email Address",p="Enter your email address"):o.toLowerCase().includes("phone")?(i="Phone Number",p="Enter your phone number"):o.toLowerCase().includes("company name")?(i="Company Name",p="Enter your company name"):o.toLowerCase().includes("type of business")?(i="Business Type",p="Enter your business type"):o.toLowerCase().includes("industry")?(i="Industry",p="Search industries..."):o.toLowerCase().includes("address")?(i="address",p="Search for your business address"):b==="number"||o.toLowerCase().includes("how many")?(i="Number of Machines",p="Enter quantity needed"):o.toLowerCase().includes("requirements")?(i="Specific Requirements",p="Tell us about your requirements"):o.toLowerCase().includes("feedback")?(i="Your Feedback",p="Please share your thoughts with us"):(i=b.charAt(0).toUpperCase()+b.slice(1),p=`Enter your ${b}`),{label:i,placeholder:p}};function We({initialMessages:b=[],onStageComplete:o,onGoalComplete:i,tools:p={},onClose:I,initialChatId:P,...r}){const[m,y]=n.useState({}),[c,W]=n.useState(null),[A]=n.useState([]),[se,Ee]=n.useState(!1),Se=n.useRef(null),[E,S]=n.useState(null),[H,Y]=n.useState(!1),[g,R]=n.useState("text"),[T,w]=n.useState(""),[_,M]=n.useState(""),[$,k]=n.useState([]),[ne,ie]=n.useState(!1),[x,re]=n.useState(null),[oe,z]=n.useState(!1),[q,L]=n.useState(!1),[ce,ue]=n.useState([]),D=n.useRef(null),de=({label:l,value:a})=>{re({label:l,value:a}),y(t=>({...t,industry:a})),O(a,l),ie(!1)},[B,K]=n.useState(!1),[Q,J]=n.useState(null),[fe,Ae]=n.useState([]),[F,pe]=n.useState(0),O=async(l,a)=>{if(J(null),(g==="email"||g==="tel")&&H){K(!0);try{const f=g==="email"?`/api/email?Email=${encodeURIComponent(l)}`:`/api/phone?Phone=${encodeURIComponent(l)}`,ge=await(await fetch(`${f}`)).json();if(!(g==="email"?ge.ResponseCode==="Valid":ge.IsValid==="Yes")){J(g==="email"?"Please enter a valid email address":"Please enter a valid phone number"),K(!1);return}}catch(f){console.error(`${g} validation error:`,f)}finally{K(!1)}}const{label:t}=Ie(g,T),s=t.toLowerCase().replace(/\s+/g,"_"),d={...m,[s]:l};if(y(d),N({role:"user",content:a||l}),E==="personal_info"&&s==="phone_number"&&d.full_name&&d.email&&d.phone_number&&Ve(d),E){const f={[s]:l,...d};if(i)switch(E){case"personal_info":g==="tel"&&C(i,"personal_info_completed",f);break;case"business_info":g==="address"&&C(i,"business_info_completed",f);break;case"product_info":g==="text"&&T.includes("requirements")&&C(i,"product_info_completed",f);break;case"feedback":C(i,"feedback_provided",f);break}o&&o(E,{[s]:l})}M(""),Y(!1),L(!1),H&&T&&(F>=fe.length-1&&Ae(f=>[...f.slice(0,F+1),{question:T,inputType:g,inputLabel:T}]),pe(f=>f+1))},xe=()=>{if(F>0){const l=fe[F-1];R(l.inputType),w(l.question),M(""),pe(a=>a-1),Y(!0)}},{messages:u,input:ye,handleInputChange:_e,handleSubmit:me,append:N,status:h}=Fe.useChat({id:P||void 0,api:r.apiUrl||"/api/chat",initialMessages:b,maxSteps:1,sendExtraMessageFields:!0,onResponse:l=>{const a=["i've initiated","i've started","quote process","quote flow","request flow"],t=l.toString().toLowerCase();a.some(s=>t.includes(s))&&console.warn("Response contains forbidden phrases:",t)},async onToolCall({toolCall:l}){var a;if((a=p[l.toolName])!=null&&a.execute)return await p[l.toolName].execute(l.args)},body:{currentProduct:r.currentProduct?{id:r.currentProduct.id||r.currentProduct.objectID,name:r.currentProduct.name||r.currentProduct.product_type,model:r.currentProduct.model_number,manufacturer:r.currentProduct.manufacturer,category:r.currentProduct.category}:null}});n.useEffect(()=>{if(u.length===0||h!=="ready")return;const l=u[u.length-1];if(l.role!=="assistant")return;const a=l.content;try{if(l.annotations&&Array.isArray(l.annotations)){const t=l.annotations.find(s=>{var d;return((d=s.other)==null?void 0:d.type)==="ui_trigger"});if(t){const s=t.other.trigger;switch(s.trigger){case"input_field":s.type,k([]),R(s.type||"text"),Y(!0),w(a.trim()),L(!0),a.includes("name")?(S("personal_info"),!E&&i&&C(i,"quote_started",{trigger:s.trigger})):a.includes("email")||a.includes("phone")?S("personal_info"):a.includes("company")||a.includes("address")?S("business_info"):a.includes("machines")?S("product_info"):a.includes("requirements")?(S("product_info"),N({role:"assistant",content:"Would you like to share feedback, please share it with us."}),i&&C(i,"quote_completed",m)):a.includes("feedback")&&i&&C(i,"feedback_provided",m);break;case"button_options":s.options,k(s.options||[]),R(s.type||"text"),w(a.trim()),S("business_info"),L(!0);break;case"sector_search":k([]),R(s.type||"text"),ie(!0),w(a.trim()),S("business_info"),L(!0);break;case"yes_no_buttons":k([]),R(s.type||"text"),z(!0),w(a.trim()),S("submitted"),L(!0);break;case"welcome_options":k([]),R(s.type||"text"),L(!1),w(a.trim());break}}}else{const t=/{(?:[^{}]|{(?:[^{}]|{[^{}]*})*})*}/g,s=a.match(t);if(s)for(const d of s)try{const f=JSON.parse(d);f.trigger}catch(f){}}}catch(t){console.error("Error processing triggers:",t)}},[u,h]);const Te=()=>{const{label:l,placeholder:a}=Ie(g,T);return e.jsxs(e.Fragment,{children:[H&&e.jsx("div",{className:"fpl-p-0","aria-label":T,children:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fpl-mb-0",children:e.jsx("label",{htmlFor:l.toLowerCase().replace(/\s+/g,"_"),"aria-label":l,className:"fpl-text-sm fpl-font-medium fpl-sr-only",children:l})}),e.jsxs("div",{className:"fpl-flex fpl-flex-col fpl-w-full",children:[e.jsxs("div",{className:"fpl-flex fpl-gap-2",children:[F>0&&V==="quote_flow"&&e.jsx(v.Button,{variant:"outline",onClick:xe,className:"fpl-flex-none","aria-label":"Back",children:"Back"}),g==="address"?e.jsx("div",{className:"fpl-flex-1",children:e.jsx(ve.AddressSearch,{id:l.toLowerCase().replace(/\s+/g,"_"),name:l.toLowerCase().replace(/\s+/g,"_"),value:_,"aria-label":"Address input",onChange:t=>M(t),onKeyDown:t=>{t.key==="Enter"&&O(_)},onSelect:(t,s)=>{M(t),y(s?d=>({...d,address:t,street:s.street,city:s.city,state:s.state,postalCode:s.postalCode,country:s.country}):d=>({...d,address:t}))},placeholder:a,children:e.jsx(v.Button,{onClick:()=>O(_),disabled:!_.trim()||B,"aria-label":"Submit address",children:B?e.jsxs("div",{className:"fpl-flex fpl-items-center",children:[e.jsxs("svg",{className:"fpl-animate-spin -ml-1 fpl-mr-2 fpl-h-4 fpl-w-4 fpl-text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"fpl-opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"fpl-opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Validating"]}):"Submit"})})}):e.jsxs(e.Fragment,{children:[e.jsx(G.Input,{id:l.toLowerCase().replace(/\s+/g,"_"),name:l.toLowerCase().replace(/\s+/g,"_"),type:g,value:_,"aria-label":l,onChange:t=>{M(t.target.value),J(null)},onKeyDown:t=>{t.key==="Enter"&&O(_)},placeholder:a,className:`fpl-flex-1 ${Q?"fpl-border-red-500":""}`}),e.jsx(v.Button,{onClick:()=>O(_),disabled:!_.trim()||B,"aria-label":"Submit input",children:B?e.jsxs("div",{className:"fpl-flex fpl-items-center",children:[e.jsxs("svg",{className:"fpl-animate-spin -ml-1 fpl-mr-2 fpl-h-4 fpl-w-4 fpl-text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"fpl-opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"fpl-opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Validating"]}):"Submit"})]})]}),Q&&e.jsx("div",{className:"fpl-text-red-500 fpl-text-sm fpl-mt-1",children:Q})]})]})}),$.length>0&&e.jsx("div",{className:"fpl-p-3",children:e.jsx("div",{id:l.toLowerCase().replace(/\s+/g,"_"),"aria-label":l.toLowerCase().replace(/\s+/g,"_"),className:"fpl-flex fpl-flex-wrap fpl-gap-2",children:$.map((t,s)=>e.jsx(v.Button,{variant:"outline","aria-label":t,onClick:()=>{ae.capitalizeFirstLetter(t),O(ae.capitalizeFirstLetter(t))},className:"focus:fpl-ring-2 focus:fpl-ring-primary",children:ae.capitalizeFirstLetter(t)},s))})}),ne&&e.jsxs("div",{className:"fpl-p-3",children:[e.jsx("label",{htmlFor:l.toLowerCase().replace(/\s+/g,"_"),"aria-label":l.toLowerCase().replace(/\s+/g,"_"),className:"fpl-mb-2 fpl-sr-only",children:"What industry are you in?"}),e.jsx(G.Input,{id:l.toLowerCase().replace(/\s+/g,"_"),type:"text",name:l.toLowerCase().replace(/\s+/g,"_"),"aria-label":l.toLowerCase().replace(/\s+/g,"_"),value:(x==null?void 0:x.label)||"",onChange:t=>{var d;const s=(d=te.filter(f=>f.label.toLowerCase().includes(t.target.value.toLowerCase())))==null?void 0:d[0];re({label:s==null?void 0:s.label,value:t.target.value})},onKeyDown:t=>{var s;if(t.key==="Enter"){const d=(s=te.filter(f=>{var le;return f.label.toLowerCase().includes(((le=x==null?void 0:x.label)==null?void 0:le.toLowerCase())||"")}))==null?void 0:s[0];d&&de({label:d.label,value:d.value})}},placeholder:"Search industries...",className:"fpl-mb-2"}),e.jsx("div",{className:"fpl-max-h-60 fpl-overflow-y-auto fpl-border fpl-rounded-md fpl-bg-gray-50 fpl-mt-1",children:te.filter(t=>{var s;return t.label.toLowerCase().includes(((s=x==null?void 0:x.label)==null?void 0:s.toLowerCase())||"")}).slice(0,10).map(t=>e.jsx("button",{value:t.value,onClick:()=>de({label:t.label,value:t.value}),className:"fpl-w-full fpl-px-4 fpl-py-2 fpl-text-left hover:fpl-bg-gray-100 fpl-border-b focus:fpl-border-b-0","aria-label":t.label,children:t.label},t.value))})]}),oe&&e.jsx("div",{className:"fpl-p-3",children:e.jsxs("div",{id:l.toLowerCase().replace(/\s+/g,"_"),"aria-label":l.toLowerCase().replace(/\s+/g,"_"),className:"fpl-flex fpl-gap-2",children:[e.jsx(v.Button,{variant:"outline","aria-label":"Yes",onClick:()=>{var d,f;const t=u[u.length-1],s=((d=t==null?void 0:t.content)==null?void 0:d.toLowerCase().includes("feedback"))||((f=t==null?void 0:t.content)==null?void 0:f.toLowerCase().includes("review"));setTimeout(()=>{N({role:"user",content:s?"I'd like to leave feedback":"Yes"}),z(!1),o&&o("completed",{})},300)},children:"Yes"}),e.jsx(v.Button,{variant:"outline","aria-label":"No",onClick:()=>{N({role:"assistant",content:"Thanks for your response."}),setTimeout(()=>{N({role:"user",content:"No thanks"}),z(!1),o&&o("completed",{})},300)},children:"No"})]})})]})},X=n.useRef(!1);n.useEffect(()=>{u.length===0&&!X.current&&(X.current=!0,(async()=>{try{r.currentProduct?(await N({role:"system",content:`You are a sales assistant for Forbes Professional, focusing on the ${r.currentProduct.name||r.currentProduct.product_type||"product"}. When discussing this product: 1. Always offer two clear choices to the user: learning more about the product OR getting a quote 2. Keep initial responses brief and focused on the product 3. Use button_options instead of yes_no_buttons when presenting choices 4. If the user wants to learn more, provide key features, benefits, and technical specifications 5. If the user wants a quote, follow the structured quote flow`,id:`product-system-${r.currentProduct.id||r.currentProduct.objectID||Date.now()}`}),await N({role:"assistant",content:`Ready to get a quote for this ${r.currentProduct.name||r.currentProduct.product_type||"product"}?`,id:`product-quote-welcome-${r.currentProduct.id||r.currentProduct.objectID||Date.now()}`,annotations:[{type:"ui_trigger",other:{trigger:{trigger:"button_options",options:["Learn more","Get quote now"]}}}],parts:[{type:"tool-invocation",toolInvocation:{state:"result",toolCallId:`product-${r.currentProduct.id||r.currentProduct.objectID||Date.now()}`,toolName:"searchProducts",args:{query:`${r.currentProduct.manufacturer} ${r.currentProduct.name||r.currentProduct.product_type}`},result:{type:"product",products:[r.currentProduct]}}}]})):(await N({role:"system",content:`You are a sales assistant for Forbes Professional, specializing in commercial laundry equipment. When greeting users: 1. Always offer clear options such as "Learn more" or "Get quote now" 2. Use button_options instead of yes_no_buttons for initial interactions 3. If the user wants to learn about products, ask about their industry needs first 4. If the user wants a quote, follow the structured quote flow sequence 5. For the quote flow, use the appropriate UI triggers: - Use input_field triggers for collecting name, email, phone, etc. - Use button_options for business type selection - Use sector_search for industry selection`,id:"general-system-message"}),await N({role:"assistant",annotations:[{type:"ui_trigger",other:{trigger:"button_options",options:["Learn more","Get quote now"]}}],content:"Welcome to Forbes Professional! I'm here to help with your commercial laundry equipment needs. Are you looking for information about specific products, service options, or would you like to request a quote?",id:"welcome-message"}))}catch(a){console.error("Failed to initialize chat:",a),X.current=!1}})())},[u.length,N,r.currentProduct]),n.useEffect(()=>{if(D.current){const l=D.current;setTimeout(()=>{l.scrollTo({top:l.scrollHeight,behavior:"smooth"})},100)}},[u,ce]);const j=(l,a)=>{y(t=>({...t,[l]:a}))},Ce=n.useCallback(()=>{const l=A.findIndex(t=>t.id===(c==null?void 0:c.id));if(l===A.length-1){if(i){let t="contact_submitted";m.appointmentDate||m.appointmentTime||A.some(s=>s.id.includes("appointment"))?t="appointment_booked":m.quoteType||m.budget||A.some(s=>s.id.includes("quote"))?t="quote_requested":(m.demoPreference||A.some(s=>s.id.includes("demo")))&&(t="demo_requested"),i(t,m)}}else W(A[l+1]),o&&o(`form_field_${c==null?void 0:c.id}`,{fieldId:c==null?void 0:c.id,value:c!=null&&c.id?m[c.id]:void 0})},[c,m,A,i]);n.useEffect(()=>{const l=u.length>0?u[u.length-1]:null;l&&l.role==="assistant"&&o&&(o("conversation_message",{messageId:l.id,messageCount:u.length}),u.length===1&&o("welcome_complete",{}))},[u,o]);const Re=l=>{if(l.isAI)return null;switch(l.type){case"select":return e.jsx(qe,{id:l.id,"aria-label":l.label,options:l.options||[],placeholder:l.placeholder||`Select ${l.label}`,value:m[l.id]||"",onChange:a=>j(l.id,a),onSelect:a=>j(l.id,a)});case"address":return e.jsx(ve.AddressSearch,{id:l.id.toLowerCase().replace(/\s+/g,"_"),name:l.id.toLowerCase().replace(/\s+/g,"_"),"aria-label":l.label,value:m[l.id]||"",onChange:a=>j(l.id,a),onSelect:a=>j(l.id,a),placeholder:l.placeholder||"Search for an address..."});case"textarea":return e.jsx(ke.Textarea,{id:l.id,"aria-label":l.label,value:m[l.id]||"",onChange:a=>j(l.id,a.target.value),placeholder:l.placeholder});default:return e.jsx(G.Input,{id:l.id,"aria-label":l.label,type:l.type,value:m[l.id]||"",onChange:a=>j(l.id,a.target.value),placeholder:l.placeholder})}},we=()=>u.length!==1&&!r.currentProduct||r.currentProduct?null:e.jsxs("div",{className:"fpl-flex fpl-flex-wrap fpl-gap-2 fpl-mt-3",children:[e.jsx(v.Button,{variant:"outline","aria-label":"Browse products",onClick:()=>N({role:"user",content:"I want to learn about your products"}),children:"Browse Products"}),e.jsx(v.Button,{variant:"outline","aria-label":"Request quote",onClick:()=>N({role:"user",content:"I'd like to request a quote"}),children:"Request Quote"}),e.jsx(v.Button,{variant:"outline","aria-label":"Service support",onClick:()=>N({role:"user",content:"I need service support"}),children:"Service Support"})]});n.useEffect(()=>{const l=u.filter(a=>a.role==="assistant"&&!ce.includes(a.id));l.length>0&&(ue(a=>[...a,...l.map(t=>t.id)]),l.forEach(a=>{setTimeout(()=>{ue(t=>t.filter(s=>s!==a.id))},1e3)}))},[u]);const Le=l=>e.jsx("div",{"aria-label":"Booking results",className:"fpl-mt-2 fpl-grid fpl-grid-cols-1 fpl-gap-4",children:l.map((a,t)=>e.jsxs("div",{"aria-label":"Booking result",className:"fpl-bg-white fpl-rounded-lg fpl-border fpl-p-3 hover:fpl-shadow-md fpl-transition-shadow",children:[e.jsx("h4",{className:"fpl-font-medium fpl-text-primary",children:a.title||"Booking Details"}),e.jsx("div",{className:"fpl-text-sm fpl-text-gray-700 fpl-mt-1",children:a.description||a.details}),a.time&&e.jsxs("div",{className:"fpl-text-xs fpl-mt-1",children:["Time: ",a.time]}),a.date&&e.jsxs("div",{className:"fpl-text-xs",children:["Date: ",a.date]})]},t))}),[V]=n.useState("initial"),[,Z]=n.useState(!1);n.useEffect(()=>{const l=u[u.length-1];if((l==null?void 0:l.role)==="assistant"){const a=l.content.toLowerCase(),t=a.includes("does this help")||a.includes("would you like")||a.includes("is this useful")||a.endsWith("?");Z((V==="completed"||V==="quote_flow"&&a.includes("quote"))&&!t)}if((l==null?void 0:l.role)==="user"){const a=l.content.toLowerCase();(a.includes("feedback")||a.includes("review")||a.includes("rate"))&&Z(!1),(a==="yes"||a.startsWith("yes,")||a==="no"||a.startsWith("no,"))&&Z(!1)}},[u,V]);const Oe=n.useRef(null),ee=n.useRef(null);n.useEffect(()=>{r.isOpen&&ee.current&&setTimeout(()=>{var l;return(l=ee.current)==null?void 0:l.focus()},100)},[r.isOpen]),n.useEffect(()=>{const l=a=>{a.key==="Escape"&&r.isOpen&&I&&I()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[r.isOpen,I]);const je=()=>{I==null||I()};n.useEffect(()=>()=>{},[]);const be=n.useCallback(()=>{if(D.current){const l=D.current;l.scrollTo({top:l.scrollHeight,behavior:"smooth"})}},[]);n.useEffect(()=>{const l=setTimeout(be,100);return()=>clearTimeout(l)},[u.length,be]);const[U,he]=n.useState(!1);n.useEffect(()=>{document.cookie.split(";").some(t=>t.trim().startsWith("fpl-privacy-"))&&he(!0)},[]);const Pe=()=>{he(!0);const l=Math.random().toString(36).substring(2,15),a=new Date;a.setDate(a.getDate()+90),document.cookie=`fpl-privacy-${l}=accepted; expires=${a.toUTCString()}; path=/; SameSite=Strict`,i&&i("privacy_accepted",{timestamp:new Date().toISOString()})},Me=()=>{o&&o("privacy_rejected",{timestamp:new Date().toISOString()}),I==null||I()};return e.jsx(e.Fragment,{children:e.jsx("div",{className:"chat-widget-container",children:e.jsxs("div",{ref:Oe,role:"dialog","aria-labelledby":r.title,"aria-describedby":r.subtitle,"aria-modal":"true",className:`chatbot-widget fpl-bg-[#f9fbff] fpl-fixed fpl-bottom-2 fpl-right-0 md:fpl-bottom-[5.5rem] md:fpl-right-4 fpl-w-full fpl-max-w-96 fpl-h-[calc(95vh-32px)] fpl-max-h-[650px] fpl-rounded-lg fpl-shadow-xl fpl-flex fpl-flex-col fpl-overflow-hidden fpl-transition-all fpl-duration-300 fpl-z-[999999999]`,children:[e.jsxs("div",{className:"fpl-absolute fpl-top-0 fpl-left-0 fpl-w-full fpl-h-full fpl-z-[-2] fpl-overflow-hidden",children:[e.jsx("div",{className:"fpl-w-full fpl-h-full",style:{background:` radial-gradient(circle at 75% 30%, white 0%, transparent 50%), radial-gradient(circle at 25% 80%,rgb(241, 244, 251) 0%, transparent 50%), radial-gradient(circle at 80% 80%,rgb(213, 232, 252) 0%, transparent 60%) `,backgroundSize:"200% 200%",animation:"gradientFlow 20s ease infinite",opacity:"0.15"}}),e.jsx("div",{className:"fpl-absolute fpl-bottom-0 fpl-left-0 fpl-w-full fpl-h-full",style:{background:"linear-gradient(to top, rgba(217, 218, 255, 0.1) 0%, rgba(215, 225, 250, 0.1) 40%, rgba(218, 223, 253, 0) 100%)",pointerEvents:"none"}}),e.jsx("style",{children:` @keyframes gradientFlow { 0% { background-position: 0% 50% } 50% { background-position: 100% 50% } 100% { background-position: 0% 80% } } `})]}),e.jsxs("div",{className:"fpl-bg-[#126dd8] fpl-text-white fpl-p-3 fpl-flex fpl-justify-between fpl-items-center",children:[e.jsx(e.Fragment,{children:e.jsxs("div",{className:"fpl-flex fpl-items-center",children:[r.logoUrl?e.jsx("img",{src:r.logoUrl,alt:"Logo",className:"fpl-h-8 fpl-w-8 fpl-mr-2"}):e.jsx("div",{className:"fpl-bg-black/70 fpl-h-[52px] fpl-w-[52px] fpl-rounded-full fpl-mr-3",children:e.jsx(Ue.default,{size:52})}),e.jsxs("div",{children:[e.jsx("h3",{className:"!fpl-text-white fpl-font-medium",children:r.title}),e.jsx("p",{className:"!fpl-text-sm !fpl-text-white fpl-opacity-80",children:r.subtitle})]})]})}),e.jsx("div",{className:"fpl-flex fpl-gap-2",children:e.jsx("button",{"aria-label":"Close chat",ref:ee,onClick:je,className:"fpl-rounded-full fpl-p-1 fpl-text-white fpl-hover:text-white/50 fpl-transition-colors",type:"button",children:e.jsx(Ge.default,{className:"fpl-w-6 fpl-h-6 flp-text-white"})})})]}),e.jsxs("div",{ref:D,className:"fpl-flex-1 fpl-overflow-y-auto fpl-p-4 fpl-space-y-4",children:[u.map((l,a)=>l.role==="system"?e.jsx(n.Fragment,{},`${l.id||a}-fragment`):e.jsx(n.Fragment,{children:l.parts&&l.parts.length>0?e.jsx(De.ChatMessage,{message:l,renderBookingResults:Le,isStreaming:h==="streaming"&&a===u.length-1},`${l.id||a}-message`):null},`${l.id||a}-fragment`)),h==="streaming"&&e.jsx("div",{className:"message-item fpl-flex fpl-justify-start fpl-mb-4",children:e.jsx(Be,{})},"typing-indicator"),u.length===1&&u[0].role==="assistant"&&e.jsx(we,{},"quick-replies"),se&&c&&e.jsxs("div",{className:"fpl-bg-white fpl-rounded-lg fpl-border fpl-p-4 fpl-my-3",children:[e.jsx("h4",{className:"fpl-font-medium fpl-mb-2",children:c.label}),e.jsxs("div",{className:"fpl-space-y-3",children:[Re(c),e.jsxs("div",{className:"fpl-flex fpl-justify-between fpl-mt-3",children:[e.jsx(v.Button,{variant:"outline",onClick:()=>Ee(!1),children:"Cancel"}),e.jsx(v.Button,{onClick:Ce,disabled:c.required&&!m[c.id],children:A.indexOf(c)<A.length-1?"Next":"Submit"})]})]})]},"form-ui"),e.jsx("div",{ref:Se},"messages-end")]}),!se&&e.jsxs("div",{className:"fpl-px-3 fpl-pb-3 fpl-min-h-[62px]",children:[!U&&E&&e.jsx(Ye,{onAccept:Pe,onReject:Me}),e.jsx("form",{onSubmit:me,className:"fpl-p-3 fpl-bg-white fpl-border fpl-shadow-sm fpl-rounded-xl",children:q&&H||q&&$.length>0||q&&ne||q&&oe?U||!E?Te():e.jsx("div",{className:"fpl-text-center fpl-py-2 fpl-text-gray-500",children:"Please accept the privacy notice to continue"}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"fpl-flex fpl-gap-2",children:[e.jsx(G.Input,{id:"message-input",name:"message-input",value:ye,onChange:_e,"aria-label":"Message input",onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),me(l))},placeholder:h==="streaming"?"Receiving response...":h==="submitted"?"Message sent...":"Type your message...",disabled:h==="streaming"||h==="submitted"||E!==null&&!U,className:`fpl-flex-1 ${h==="streaming"||h==="submitted"||E!==null&&!U?"bg-gray-50":""}`}),e.jsx(v.Button,{type:"submit","aria-label":"Send message",disabled:h==="streaming"||h==="submitted"||E!==null&&!U,className:`fpl-transition-all ${h==="streaming"?"bg-blue-400":h==="submitted"?"bg-blue-500":""}`,children:h==="streaming"?e.jsx(Ne,{}):h==="submitted"?e.jsx(Ne,{}):e.jsx(He.default,{})})]})})})]}),process.env.NODE_ENV==="development"&&e.jsx("div",{className:"fpl-mt-4",children:e.jsx("button",{className:"fpl-px-4 fpl-py-2 fpl-bg-blue-500 fpl-text-white fpl-rounded",onClick:()=>{i?i("test_goal",{testData:"This is a test goal",timestamp:new Date().toISOString()}):console.error("onGoalComplete is not defined")},children:"Test Goal Event"})})]})})})}const Ye=({onAccept:b,onReject:o})=>e.jsxs("div",{className:"fpl-p-3 fpl-bg-black fpl-border fpl-border-gray-800 fpl-rounded-lg fpl-shadow-md fpl-mb-3 fpl-text-white fpl-text-sm",children:[e.jsx("h4",{className:"fpl-font-bold fpl-mb-2 fpl-text-sm fpl-text-white",children:"Privacy Notice"}),e.jsx("p",{className:"fpl-mb-2 fpl-text-sm fpl-text-white",children:"This is an AI Agent managed and developed by Forbes Professional. When you use our chat service, your interactions and information are stored in our secure databases hosted in the UK."}),e.jsx("p",{className:"fpl-mb-2 fpl-text-sm fpl-text-white",children:"For quote requests, we'll collect necessary information (email, phone, address, company name, etc.) which is processed through Segment for analytics and stored in our Hubspot CRM."}),e.jsx("p",{className:"fpl-mb-2 fpl-text-sm fpl-text-white",children:"By accepting, you consent to our sales team contacting you regarding your inquiry and relevant services."}),e.jsx("p",{className:"fpl-mb-2 fpl-text-sm fpl-text-white",children:"We use various AI models powered by Anthropic to deliver this service and improve your experience."}),e.jsx("p",{className:"fpl-mb-3",children:e.jsx("a",{href:"/legal/privacy-policy",target:"_blank",rel:"noopener noreferrer",className:"fpl-text-blue-400 fpl-underline fpl-text-sm",children:"Read our full Privacy Policy"})}),e.jsxs("div",{className:"fpl-flex fpl-gap-2 fpl-mt-3",children:[e.jsx(v.Button,{onClick:b,className:"fpl-bg-white hover:fpl-bg-white/80 !fpl-text-black hover:!fpl-text-black/70 fpl-border-0",children:"Accept & Continue"}),e.jsx(v.Button,{variant:"outline",onClick:o,className:"fpl-border-gray-700 !fpl-text-gray-100 hover:fpl-bg-gray-800 hover:!fpl-text-gray-100 fpl-bg-transparent",children:"Decline"})]})]});exports.ChatbotWidget=We;