"use client";

import { FormEvent, useEffect, useState } from "react";
import Link from "next/link";

type CrispCommand = ["safe", boolean] | ["config", string, [boolean | number]] | ["on", string, (...args: never[]) => void] | ["set", string, unknown[]] | ["do", string, unknown[]?];

declare global {
  interface Window {
    $crisp?: { push(command: CrispCommand): void };
    CRISP_WEBSITE_ID?: string;
    CRISP_READY_TRIGGER?: () => void;
  }
}

const topics = ["Start a Project","General Inquiry","Technical Support","Partnership","Training","Product Question","Careers","Other"];

export function LiveChat({ websiteId }: { websiteId: string }) {
  const configured = /^[0-9a-f-]{36}$/i.test(websiteId);
  const [available,setAvailable]=useState<boolean|null>(null);
  const [ready,setReady]=useState(false);
  const [topic,setTopic]=useState(topics[0]);

  useEffect(()=>{
    if(!configured)return;
    window.$crisp=window.$crisp||[];
    window.CRISP_WEBSITE_ID=websiteId;
    window.$crisp.push(["safe",true]);
    window.$crisp.push(["config","hide:on:mobile",[false]]);
    window.$crisp.push(["config","hide:on:away",[false]]);
    window.$crisp.push(["config","availability:tooltip",[false]]);
    window.$crisp.push(["config","show:operator:count",[false]]);
    window.$crisp.push(["config","container:index",[190]]);
    window.$crisp.push(["do","chat:hide"]);
    window.$crisp.push(["on","website:availability:changed",((isAvailable:boolean)=>setAvailable(isAvailable)) as (...args:never[])=>void]);
    window.CRISP_READY_TRIGGER=()=>{setReady(true);setAvailable(Boolean(window.$crisp && "is" in window.$crisp && (window.$crisp as unknown as {is:(key:string)=>boolean}).is("website:available")));};
    if(!document.querySelector('script[data-niosus-chat]')){
      const script=document.createElement("script");
      script.src="https://client.crisp.chat/l.js";
      script.async=true;
      script.dataset.niosusChat="true";
      document.head.appendChild(script);
    }
  },[configured,websiteId]);

  function launch(event:FormEvent<HTMLFormElement>){
    event.preventDefault();
    if(!configured||!window.$crisp)return;
    const data=new FormData(event.currentTarget);
    const name=String(data.get("chatName")||"").trim();
    const email=String(data.get("chatEmail")||"").trim();
    const message=String(data.get("chatMessage")||"").trim();
    if(String(data.get("chatWebsite")||"").trim())return;
    window.$crisp.push(["set","user:nickname",[name]]);
    window.$crisp.push(["set","user:email",[email]]);
    window.$crisp.push(["set","session:data",[[["inquiry_topic",topic],["entry_page",window.location.pathname]]]]);
    window.$crisp.push(["set","session:segments",[[`topic-${topic.toLowerCase().replaceAll(" ","-")}`],true]]);
    window.$crisp.push(["do","chat:show"]);
    window.$crisp.push(["do","chat:open"]);
    window.$crisp.push(["do","message:send",["text",`Topic: ${topic}\n\n${message}`]]);
    (event.currentTarget.closest("details") as HTMLDetailsElement|null)?.removeAttribute("open");
  }

  const statusLabel=!configured?"Chat setup pending":available===true?"Team online":available===false?"Team offline":ready?"Checking availability":"Connecting";

  return <details className="live-chat">
    <summary className="chat-launcher">
      <span className={`chat-launcher-status ${available===true?"online":""}`} aria-live="polite"><i/>{available===true?"Online":configured?"Message us":"Chat pending"}</span>
      <b><span className="chat-open-label">Live chat</span><span className="chat-close-label">Minimize</span></b><span aria-hidden="true"><i className="chat-open-label">↗</i><i className="chat-close-label">—</i></span>
    </summary>
    <section className="chat-panel" id="niosus-chat-panel" role="region" aria-labelledby="niosus-chat-heading">
      <header><div><span className={`chat-status ${available===true?"online":""}`} aria-live="polite"><i/>{statusLabel}</span><h2 id="niosus-chat-heading">How can we help?</h2></div><button type="button" onClick={event=>(event.currentTarget.closest("details") as HTMLDetailsElement|null)?.removeAttribute("open")} aria-label="Minimize chat">—</button></header>
      {configured?<form onSubmit={launch}>
        <p>{available===true?"A team member is available. Start with a little context.":"Send a message now. The team can reply here and by email when available."}</p>
        <div><label htmlFor="chat-name">Name</label><input id="chat-name" name="chatName" required autoComplete="name" maxLength={120} placeholder="Your name"/></div>
        <div><label htmlFor="chat-email">Email</label><input id="chat-email" name="chatEmail" type="email" required autoComplete="email" maxLength={254} placeholder="you@company.com"/></div>
        <div><label htmlFor="chat-topic">Topic</label><select id="chat-topic" name="chatTopic" value={topic} onChange={event=>setTopic(event.target.value)}>{topics.map(item=><option key={item}>{item}</option>)}</select></div>
        <div><label htmlFor="chat-message">Message</label><textarea id="chat-message" name="chatMessage" required rows={4} maxLength={2000} placeholder="Give us the useful context."/></div>
        <input className="chat-trap" name="chatWebsite" tabIndex={-1} autoComplete="off" aria-hidden="true"/>
        <label className="chat-consent"><input type="checkbox" required/><span>I agree to the <Link href="/privacy-policy" target="_blank" rel="noopener noreferrer">Privacy Policy</Link>.</span></label>
        <button className="chat-start" type="submit">{available===true?"Start live chat":"Send offline message"} <span>↗</span></button>
      </form>:<div className="chat-unconfigured"><p>Live chat is not connected yet. Use the secure inquiry form and the NIOSUS team will respond by your preferred contact method.</p><Link href={`/contact?topic=${encodeURIComponent(topic)}`} className="chat-start">Open secure inquiry <span>↗</span></Link></div>}
      <footer>Powered by Crisp · No automated availability claims</footer>
    </section>
  </details>
}
