/* global React */

/*
  Vapi voice + chat assistant section.

  To activate, replace the placeholder values in VAPI_CONFIG below with your
  real Vapi public API key and assistant ID from the Vapi dashboard
  (https://dashboard.vapi.ai). The component will load the Vapi Web SDK
  on demand and start a real voice session.

  Until you do, clicking "Start call" will surface a friendly setup notice
  and the chat will run a local scripted demo so you can preview the UI.
*/
const VAPI_CONFIG = /*EDITMODE-BEGIN*/{
  "publicKey": "db4bec70-a158-4897-8d0c-f8c82c89cb72",
  "assistantId": "b1ab6148-438e-4563-a679-de7ddf5ae9d4"
}/*EDITMODE-END*/;

const isConfigured = () =>
  VAPI_CONFIG.publicKey && !VAPI_CONFIG.publicKey.startsWith("YOUR_") &&
  VAPI_CONFIG.assistantId && !VAPI_CONFIG.assistantId.startsWith("YOUR_");

// Singleton Vapi instance — initialized on first call using the html-script-tag SDK
// (loaded via <script async> in index.html as window.vapiSDK)
let _vapiInstance = null;
const getVapiInstance = () => {
  if (_vapiInstance) return _vapiInstance;
  if (!window.vapiSDK) throw new Error("Vapi SDK not ready yet — please try again in a moment.");
  _vapiInstance = window.vapiSDK.run({
    apiKey: VAPI_CONFIG.publicKey,
    assistant: VAPI_CONFIG.assistantId,
    config: { position: "bottom-right", offset: "-9999px" }, // hide the built-in button widget
  });
  return _vapiInstance;
};

/* ===== Visual: animated mic / waveform ===== */
const Waveform = ({ active }) => (
  <div className="vapi-wave" aria-hidden="true">
    {[0,1,2,3,4,5,6,7,8,9,10,11].map(i => (
      <span key={i} style={{ animationDelay: `${(i % 6) * 0.08}s`, opacity: active ? 1 : 0.35 }} />
    ))}
  </div>
);

/* ===== The Call panel ===== */
const CallPanel = () => {
  const [state, setState] = React.useState("idle"); // idle | connecting | active | error
  const [message, setMessage] = React.useState("");
  const [muted, setMuted] = React.useState(false);
  const [duration, setDuration] = React.useState(0);
  const vapiRef = React.useRef(null);
  const tickRef = React.useRef(null);

  React.useEffect(() => () => {
    if (vapiRef.current) try { vapiRef.current.stop(); } catch (e) {}
    if (tickRef.current) clearInterval(tickRef.current);
  }, []);

  React.useEffect(() => {
    if (state === "active") {
      setDuration(0);
      tickRef.current = setInterval(() => setDuration(d => d + 1), 1000);
    } else if (tickRef.current) {
      clearInterval(tickRef.current);
      tickRef.current = null;
    }
  }, [state]);

  const startCall = async () => {
    setMessage("");
    if (!isConfigured()) {
      setState("error");
      setMessage("Voice assistant isn't connected yet. Add your Vapi public key and assistant ID in components/VapiAssistant.jsx to enable live calls. (Until then, you can still call us at (209) 728‑1234.)");
      return;
    }
    try {
      setState("connecting");
      const vapi = getVapiInstance();

      if (!vapiRef.current) {
        vapiRef.current = vapi;
        vapi.on("call-start", () => setState("active"));
        vapi.on("call-end", () => setState("idle"));
        vapi.on("error", (e) => {
          console.error("Vapi error event:", e);
          setState("error");
          setMessage(e?.errorMsg || e?.message || e?.error?.message || JSON.stringify(e) || "Couldn't connect. Please try again or call (209) 728‑1234.");
        });
      }

      await vapi.start(VAPI_CONFIG.assistantId);
    } catch (err) {
      console.error("Vapi startCall error:", err);
      setState("error");
      setMessage(err?.message || err?.toString() || "Couldn't start the call. Please try again.");
    }
  };

  const endCall = () => {
    if (vapiRef.current) try { vapiRef.current.stop(); } catch (e) {}
    setState("idle");
  };

  const toggleMute = () => {
    if (!vapiRef.current) return;
    const next = !muted;
    try { vapiRef.current.setMuted(next); setMuted(next); } catch (e) {}
  };

  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;

  return (
    <div className="vapi-panel call-panel">
      <div className="vapi-panel-head">
        <div className="vapi-tag">Voice</div>
        <h3>Talk to our virtual receptionist</h3>
        <p>Ask about our services, request an estimate, or just see if we work in your area. Available 24/7.</p>
      </div>

      <div className={`vapi-orb state-${state}`}>
        <div className="orb-rings"><span></span><span></span><span></span></div>
        <button
          className="orb-btn"
          onClick={state === "active" ? endCall : startCall}
          disabled={state === "connecting"}
          aria-label={state === "active" ? "End call" : "Start call"}
        >
          {state === "active" ? (
            <svg width="36" height="36" viewBox="0 0 24 24" fill="currentColor">
              <rect x="6" y="6" width="12" height="12" rx="1.5" />
            </svg>
          ) : state === "connecting" ? (
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83">
                <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite" />
              </path>
            </svg>
          ) : (
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72 12.84 12.84 0 00.7 2.81 2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7A2 2 0 0122 16.92z" />
            </svg>
          )}
        </button>
      </div>

      <Waveform active={state === "active"} />

      <div className="vapi-status">
        {state === "idle" && <span className="dim">Tap to start a voice call</span>}
        {state === "connecting" && <span>Connecting…</span>}
        {state === "active" && <span className="live"><span className="pulse"></span>Live · {fmt(duration)}</span>}
        {state === "error" && <span className="err">Couldn't connect</span>}
      </div>

      {state === "active" && (
        <div className="vapi-actions">
          <button className="btn-mini" onClick={toggleMute}>
            {muted ? "Unmute" : "Mute"}
          </button>
          <button className="btn-mini end" onClick={endCall}>End call</button>
        </div>
      )}

      {message && <div className="vapi-message">{message}</div>}

      <div className="vapi-foot">
        Prefer a human? Call <a href="tel:+12097281234">(209) 728‑1234</a>
      </div>
    </div>
  );
};

/* ===== The Chat panel ===== */
const ChatPanel = () => {
  const [messages, setMessages] = React.useState([
    { who: "bot", text: "Hi there — I'm Fillmore Construction's assistant. Ask me about our services, scheduling, or service area. I'll text Tom or Cole anything I can't answer." },
  ]);
  const [input, setInput] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async (text) => {
    const t = (text ?? input).trim();
    if (!t || sending) return;
    setMessages(m => [...m, { who: "user", text: t }]);
    setInput("");
    setSending(true);

    // Local scripted bot: light keyword routing so the demo feels alive.
    // Replace with a real Vapi chat call when ready.
    const reply = await new Promise(r => setTimeout(() => r(localBotReply(t)), 700));
    setMessages(m => [...m, { who: "bot", text: reply }]);
    setSending(false);
  };

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

  const quickReplies = [
    "How much for a deck?",
    "Do you serve Arnold?",
    "Can you fix a leaky roof this week?",
    "Are you licensed?",
  ];

  return (
    <div className="vapi-panel chat-panel">
      <div className="vapi-panel-head">
        <div className="vapi-tag">Chat</div>
        <h3>Send a quick message</h3>
        <p>Faster than a form, no phone tag. Replies in plain English.</p>
      </div>

      <div className="chat-window" ref={scrollRef}>
        {messages.map((m, i) => (
          <div key={i} className={`bubble ${m.who}`}>
            {m.who === "bot" && <div className="bot-avatar">F</div>}
            <div className="bubble-body">{m.text}</div>
          </div>
        ))}
        {sending && (
          <div className="bubble bot">
            <div className="bot-avatar">F</div>
            <div className="bubble-body typing"><span></span><span></span><span></span></div>
          </div>
        )}
      </div>

      {messages.length <= 2 && (
        <div className="quick-replies">
          {quickReplies.map(q => (
            <button key={q} className="qr-btn" onClick={() => send(q)}>{q}</button>
          ))}
        </div>
      )}

      <div className="chat-input">
        <input
          type="text"
          placeholder="Ask anything…"
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={onKey}
        />
        <button onClick={() => send()} disabled={!input.trim() || sending} aria-label="Send">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <path d="M5 12h14M13 6l6 6-6 6"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

/* Tiny local bot for the chat demo. Replace with a real Vapi backend call. */
function localBotReply(t) {
  const q = t.toLowerCase();
  if (/(price|cost|how much|estimate|quote)/.test(q))
    return "Estimates are free in our service area. Most decks run $45–$85 per square foot installed depending on materials. Want me to set up a callback for a real number on your project?";
  if (/(arnold|murphys|angels|vallecito|avery|dorrington|where|service area|do you serve)/.test(q))
    return "Yes — we serve Murphys, Arnold, Angels Camp, Vallecito, Avery, Dorrington and the rest of Calaveras County along the Highway 4 corridor. What town are you in?";
  if (/(roof|leak|storm|emergency|urgent|asap)/.test(q))
    return "We keep a couple of slots open each week for urgent repairs. If it's actively leaking, call (209) 728‑1234 and Tom will route the closest crew. I can also pass along your address now if you'd like.";
  if (/(license|insured|bonded|cslb|legit)/.test(q))
    return "We're CSLB License #487201, fully bonded and insured. Happy to email you a current insurance certificate before any work begins.";
  if (/(hour|open|closed|when)/.test(q))
    return "Shop hours are Monday through Friday, 7am–5pm, and Saturdays by appointment. After-hours messages here go straight to Cole's phone.";
  if (/(deck|patio|pergola|outdoor)/.test(q))
    return "Decks are our bread and butter. We do redwood, cedar, and composite — most builds take 1–2 weeks once we start. Want me to start a quote request?";
  if (/(thanks|thank you|thx)/.test(q))
    return "Anytime. We'll be here when you're ready to talk specifics.";
  return "Good question — let me have Tom or Cole get back to you on that. Want to leave your number, or should I open the estimate form?";
}

/* ===== The full section ===== */
const VapiAssistant = () => {
  return (
    <section className="section vapi-section" id="assistant" data-screen-label="08 Assistant">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">Talk to us, your way</div>
            <h2>Call or chat — anytime, no waiting on hold.</h2>
          </div>
          <p className="lede">
            We answer our own phones during business hours, but folks ask us questions
            at all hours. Our virtual receptionist can take a voice call or a text chat
            right here on the page, and she'll loop in Tom or Cole when needed.
          </p>
        </div>

        <div className="vapi-grid">
          <CallPanel />
          <ChatPanel />
        </div>

      </div>
    </section>
  );
};

window.VapiAssistant = VapiAssistant;
