/* global React */
const { useState, useEffect } = React;

/* ============================================================
   Reusable widget pieces — used across all states & variants
   ============================================================ */

const I = {
  Chat: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M21 12a9 9 0 0 1-13.4 7.8L3 21l1.2-4.6A9 9 0 1 1 21 12z"/></svg>,
  Send: () => <svg viewBox="0 0 24 24" fill="currentColor"><path d="M2 21l21-9L2 3v7l15 2-15 2z"/></svg>,
  Mic: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3zM5 11a7 7 0 0 0 14 0M12 18v3"/></svg>,
  Clip: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 11l-9 9a5 5 0 0 1-7-7l9-9a3 3 0 0 1 4 4l-9 9a1 1 0 0 1-2-2l8-8"/></svg>,
  Smile: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><circle cx="9" cy="10" r="0.8" fill="currentColor"/><circle cx="15" cy="10" r="0.8" fill="currentColor"/></svg>,
  X: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M6 6l12 12M18 6L6 18"/></svg>,
  Min: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12h14"/></svg>,
  More: () => <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></svg>,
  Stop: () => <svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>,
};

/* === Header === */
function Head({ name="Praatbox", agentName="AI Assistant", status="online", variant="default" }) {
  const isEd = variant === "editorial";
  return (
    <div className="w-head">
      <div className="w-head__avatar">{isEd ? <em style={{fontStyle:"italic"}}>P</em> : "P"}</div>
      <div>
        <div className="w-head__name">{isEd ? <>{agentName.split(" ")[0]} <em style={{color:"var(--w-accent)",fontStyle:"italic"}}>{agentName.split(" ").slice(1).join(" ")}</em></> : agentName}</div>
        <div className={`w-head__status ${status==="waiting"?"is-waiting":""} ${status==="offline"?"is-offline":""}`}>
          {status === "online" && "Online · replies in seconds"}
          {status === "waiting" && "Connecting to agent…"}
          {status === "live" && "Sara · Live agent"}
          {status === "offline" && "Offline · we'll email you back"}
        </div>
      </div>
      <div className="w-head__actions">
        <button className="w-head__btn"><I.More /></button>
        <button className="w-head__btn"><I.Min /></button>
      </div>
    </div>
  );
}

/* === Footer === */
function Foot({ show=true }) {
  if (!show) return null;
  return <div className="w-foot">POWERED BY <em>praatbox</em></div>;
}

/* === Bubble === */
function Bubble({ unread = 0 }) {
  return (
    <div className="w-bubble">
      <I.Chat />
      {unread > 0 && <span className="w-bubble__dot">{unread}</span>}
    </div>
  );
}

/* === Proactive popup === */
function Proactive() {
  return (
    <>
      <div className="w-proactive">
        <button className="w-proactive__close"><I.X /></button>
        <div className="w-proactive__avatar">P</div>
        <div>
          Looking for shipping info?<br/>
          <span style={{color:"var(--w-muted)",fontSize:12.5}}>I read every doc — ask me anything.</span>
        </div>
      </div>
      <Bubble />
    </>
  );
}

/* === A standard message === */
function Msg({ role, children, time }) {
  return (
    <div className="w-msg-row" style={{ alignSelf: role === "user" ? "flex-end" : role === "system" ? "center" : "flex-start", maxWidth: role === "system" ? "100%" : "78%" }}>
      <div className={`w-msg ${role === "user" ? "is-user" : role === "system" ? "is-system" : "is-bot"}`}>
        {children}
      </div>
      {time && role !== "system" && <span className="w-msg__time" style={{ alignSelf: role === "user" ? "flex-end" : "flex-start", paddingLeft: role === "user" ? 0 : 4, paddingRight: role === "user" ? 4 : 0 }}>{time}</span>}
    </div>
  );
}

/* === Typing indicator === */
function Typing() {
  return <div className="w-typing"><span></span><span></span><span></span></div>;
}

/* === Suggested reply chips === */
function Chips({ items, onPick }) {
  return (
    <div className="w-chips">
      {items.map((c) => <button key={c} className="w-chip" onClick={() => onPick && onPick(c)}>{c}</button>)}
    </div>
  );
}

/* === Input row === */
function Input({ value="", placeholder="Type your message…", onSend, recording=false, transcribing=false }) {
  return (
    <div className="w-input">
      <button className="w-input__btn"><I.Smile /></button>
      <button className="w-input__btn"><I.Clip /></button>
      <input
        type="text"
        defaultValue={value}
        placeholder={recording ? "🔴 Recording…" : transcribing ? "Transcribing…" : placeholder}
      />
      <button className={`w-input__btn ${recording ? "is-rec" : ""}`}><I.Mic /></button>
      <button className="w-input__btn is-send" onClick={onSend}><I.Send /></button>
    </div>
  );
}

/* === Voice recording overlay === */
function VoiceRecording() {
  return (
    <div className="w-voice">
      <div className="w-voice__pulse"><I.Mic /></div>
      <div className="w-voice__waves">
        {Array.from({length: 14}, (_, i) => <div key={i} className="w-voice__wave" style={{animationDelay:`${i*0.07}s`}}></div>)}
      </div>
      <div className="w-voice__time">0:08</div>
      <div className="w-voice__label">Listening — speak in any language.</div>
      <div className="w-voice__actions">
        <button className="w-voice__action">Cancel</button>
        <button className="w-voice__action is-stop"><I.Stop /> Stop &amp; send</button>
      </div>
    </div>
  );
}

/* === Pre-chat form === */
function PreChat() {
  return (
    <div className="w-form">
      <div>
        <h3 className="w-form__greet">Hi there. <em>Quick intro?</em></h3>
        <p className="w-form__sub">So we can keep your conversation if you need to come back later.</p>
      </div>
      <div className="w-form__field"><label>Your name</label><input placeholder="Anouk de Vries" /></div>
      <div className="w-form__field"><label>Email</label><input placeholder="anouk@glodinas.nl" type="email" /></div>
      <button className="w-form__btn">Start conversation →</button>
      <button className="w-form__skip">Continue without details</button>
    </div>
  );
}

/* === Handoff banner === */
function Handoff() {
  return (
    <div className="w-handoff">
      <div className="w-handoff__head">
        <div className="w-handoff__avatars">
          <div style={{background:"#fde68a",color:"#92400e"}}>SR</div>
          <div style={{background:"var(--w-accent)",color:"var(--w-accent-ink)"}}>P</div>
        </div>
        <div>
          <div className="w-handoff__title">Connecting you with Sara</div>
          <div className="w-handoff__sub">Support specialist · usually replies in &lt; 2 min</div>
        </div>
      </div>
      <div className="w-handoff__progress"></div>
    </div>
  );
}

/* === CSAT === */
function CSAT() {
  const [rating, setRating] = useState(4);
  return (
    <div className="w-csat">
      <h3 className="w-csat__title">How did we <em>do?</em></h3>
      <p className="w-csat__sub">Sara just resolved your conversation — rate the experience.</p>
      <div className="w-csat__stars">
        {[1,2,3,4,5].map((n) => (
          <button key={n} className={`w-csat__star ${n <= rating ? "is-filled" : ""}`} onClick={() => setRating(n)}>★</button>
        ))}
      </div>
      <textarea className="w-csat__feedback" rows="3" placeholder="Anything we should know? (optional)"></textarea>
      <button className="w-csat__btn">Submit feedback</button>
    </div>
  );
}

/* === Offline / email capture === */
function Offline() {
  return (
    <>
      <div className="w-offline">
        <div>
          <h3 className="w-offline__title">We're <em>away</em> until 9.</h3>
          <p className="w-offline__sub">Drop your email and we'll reply first thing tomorrow morning — usually before you've finished your coffee.</p>
        </div>
        <div className="w-form__field"><label>Your name</label><input placeholder="Anouk de Vries" /></div>
        <div className="w-form__field"><label>Email</label><input placeholder="anouk@glodinas.nl" type="email" /></div>
        <div className="w-form__field"><label>What's up?</label><input placeholder="A few words is plenty" /></div>
        <button className="w-form__btn">Send message →</button>
      </div>
    </>
  );
}

/* === SETTINGS panel === */
function Settings() {
  return (
    <div className="w-form" style={{gap:18}}>
      <div>
        <h3 className="w-form__greet">Settings</h3>
        <p className="w-form__sub">Tune the conversation to your liking.</p>
      </div>
      <div className="w-form__field" style={{flexDirection:"row",justifyContent:"space-between",alignItems:"center"}}>
        <label style={{textTransform:"none",letterSpacing:0,fontFamily:"inherit",fontSize:14,color:"var(--w-ink)"}}>Sound on new message</label>
        <div style={{width:38,height:22,borderRadius:11,background:"var(--w-accent)",position:"relative"}}><div style={{width:18,height:18,borderRadius:"50%",background:"white",position:"absolute",right:2,top:2}}></div></div>
      </div>
      <div className="w-form__field" style={{flexDirection:"row",justifyContent:"space-between",alignItems:"center"}}>
        <label style={{textTransform:"none",letterSpacing:0,fontFamily:"inherit",fontSize:14,color:"var(--w-ink)"}}>Save my conversation history</label>
        <div style={{width:38,height:22,borderRadius:11,background:"var(--w-accent)",position:"relative"}}><div style={{width:18,height:18,borderRadius:"50%",background:"white",position:"absolute",right:2,top:2}}></div></div>
      </div>
      <div className="w-form__field" style={{flexDirection:"row",justifyContent:"space-between",alignItems:"center"}}>
        <label style={{textTransform:"none",letterSpacing:0,fontFamily:"inherit",fontSize:14,color:"var(--w-ink)"}}>Use voice input</label>
        <div style={{width:38,height:22,borderRadius:11,background:"var(--w-line)",position:"relative"}}><div style={{width:18,height:18,borderRadius:"50%",background:"white",position:"absolute",left:2,top:2}}></div></div>
      </div>
      <div className="w-form__field">
        <label>Language</label>
        <select style={{background:"var(--w-paper)",border:"1px solid var(--w-line)",borderRadius:10,padding:"10px 12px",fontFamily:"inherit",fontSize:14,color:"var(--w-ink)"}}><option>Auto-detect</option><option>English</option><option>Nederlands</option><option>Deutsch</option><option>Français</option></select>
      </div>
      <button className="w-form__skip" style={{marginTop:"auto",alignSelf:"flex-start"}}>Clear conversation history</button>
    </div>
  );
}

/* === starter questions empty-state === */
function Starters({ items, intro }) {
  return (
    <div className="w-starters">
      {intro && <div className="w-starters__intro">{intro}</div>}
      {items.map((q) => <button key={q} className="w-starter">{q}</button>)}
    </div>
  );
}

Object.assign(window, { I, Head, Foot, Bubble, Proactive, Msg, Typing, Chips, Input, VoiceRecording, PreChat, Handoff, CSAT, Offline, Settings, Starters });
