/* chatbot.jsx — triage drawer. Diagnoses → routes to a lever card. Never sells. */

const BOT_TREE = {
  root: {
    bot: "Hey — I'm the router. Tell me where you're stuck and I'll point at the lever that fits. No pitch.",
    suggestions: [
      { label: "I'm scaling and stuck on creative.", next: "creative_stuck" },
      { label: "I need a person, not a tool.", next: "need_human" },
      { label: "My catalog is a mess.", next: "catalog_mess" },
      { label: "Just browsing — show me something.", next: "browsing" },
    ],
  },

  creative_stuck: {
    user: "I'm scaling and stuck on creative.",
    bot: "Got it. Quick check — is the bottleneck volume (need more variants weekly) or quality (the ones you have aren't converting)?",
    suggestions: [
      { label: "Volume. I need 30+ a week.", next: "creative_volume" },
      { label: "Quality. Mine look generic.", next: "creative_quality" },
    ],
  },
  creative_volume: {
    user: "Volume. I need 30+ a week.",
    bot: "Then you want the Creative Engine. It eats product photos and spits out batches of campaign-ready variants. Cheaper than a studio, no booking lag.",
    surface: "creative",
  },
  creative_quality: {
    user: "Quality. Mine look generic.",
    bot: "That's a taste problem, not a tool problem. Reel-Stack — vetted creatives who've done this for stores like yours. A human, not a slot machine.",
    surface: "reel",
  },

  need_human: {
    user: "I need a person, not a tool.",
    bot: "Fair. What kind — someone to make creative, someone to think strategy, or someone to build ops?",
    suggestions: [
      { label: "Creative.", next: "human_creative" },
      { label: "Ops / systems.", next: "human_ops" },
    ],
  },
  human_creative: {
    user: "Creative.",
    bot: "Reel-Stack. Roster of editors, performance creatives, and founder-voice writers. All vetted on e-com work. You brief, they ship.",
    surface: "reel",
  },
  human_ops: {
    user: "Ops / systems.",
    bot: "Airtable Build. We design a custom ops backbone — orders, returns, talent, content — in one base. Premium and worth it. Waitlist's open.",
    surface: "airtable",
  },

  catalog_mess: {
    user: "My catalog is a mess.",
    bot: "Product Catalog. It enriches your existing data — taxonomy, variants, alt-text, schema — so you set it once and stop hand-editing. On the waitlist now.",
    surface: "catalog",
  },

  browsing: {
    user: "Just browsing — show me something.",
    bot: "Then start with The Drop. One letter a month, written for operators. If anything in it clicks, you'll find the right lever from there.",
    surface: "drop",
  },
};

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

function SurfaceCard({ lever }) {
  const display = lever.name.replace(lever.italic, "");
  return (
    <div className="bot-card-surface">
      <div className="bot-card-surface-label">Routed to · {lever.num}</div>
      <div className="bot-card-surface-title">{display}<em>{lever.italic}</em></div>
      <div className="bot-card-surface-job">{lever.job}</div>
      <button className="bot-card-surface-cta">
        {lever.cta}
        <svg width="11" height="9" viewBox="0 0 12 10" fill="none" aria-hidden="true">
          <path d="M1 5h10M7 1l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square"/>
        </svg>
      </button>
    </div>
  );
}

function Chatbot({ open, onClose, accent }) {
  const [messages, setMessages] = React.useState([
    { from: "bot", text: BOT_TREE.root.bot },
  ]);
  const [suggestions, setSuggestions] = React.useState(BOT_TREE.root.suggestions);
  const [typing, setTyping] = React.useState(false);
  const bodyRef = React.useRef(null);

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

  const pick = (node) => {
    const step = BOT_TREE[node];
    if (!step) return;
    // user message
    setMessages(m => [...m, { from: "user", text: step.user }]);
    setSuggestions([]);
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      const append = [{ from: "bot", text: step.bot }];
      if (step.surface) {
        const lever = LEVERS.find(l => l.id === step.surface);
        if (lever) append.push({ from: "bot", surface: lever });
      }
      setMessages(m => [...m, ...append]);
      if (step.suggestions) {
        setSuggestions(step.suggestions);
      } else if (step.surface) {
        setSuggestions([
          { label: "Show me a different lever.", next: "root" },
          { label: "That works. Thanks.", next: "closer" },
        ]);
      } else {
        setSuggestions([]);
      }
    }, 700);
  };

  const restart = () => {
    setMessages([{ from: "bot", text: BOT_TREE.root.bot }]);
    setSuggestions(BOT_TREE.root.suggestions);
  };

  const handleSuggestion = (s) => {
    if (s.next === "root") {
      setMessages(m => [...m, { from: "user", text: s.label }]);
      setSuggestions([]);
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMessages(m => [...m, { from: "bot", text: "Sure. Where else are you stuck?" }]);
        setSuggestions(BOT_TREE.root.suggestions);
      }, 550);
    } else if (s.next === "closer") {
      setMessages(m => [...m, { from: "user", text: s.label }]);
      setSuggestions([]);
      setTyping(true);
      setTimeout(() => {
        setTyping(false);
        setMessages(m => [...m, { from: "bot", text: "Anytime. The cards stay where they are if you want to come back." }]);
      }, 500);
    } else {
      pick(s.next);
    }
  };

  return (
    <div className={`bot-drawer${open ? " is-open" : ""}`} role="dialog" aria-label="Router triage">
      <div className="bot-head">
        <div className="bot-head-l">
          <div className="bot-head-icon" style={{ background: accent }}>R</div>
          <div>
            <div className="bot-head-title">The Router</div>
            <div className="bot-head-sub">Diagnosis, not delivery</div>
          </div>
        </div>
        <button className="bot-head-close" onClick={onClose} aria-label="Close">✕</button>
      </div>

      <div className="bot-body" ref={bodyRef}>
        {messages.map((m, i) => {
          if (m.surface) return <SurfaceCard key={i} lever={m.surface} />;
          return <div key={i} className={`bot-msg from-${m.from}`}>{m.text}</div>;
        })}
        {typing && <Typing />}
      </div>

      {suggestions.length > 0 && (
        <div className="bot-suggest">
          <div className="bot-suggest-label">
            {messages.length <= 1 ? "Try one →" : "Or pick"}
          </div>
          {suggestions.map((s, i) => (
            <button key={i} className="bot-chip" onClick={() => handleSuggestion(s)}>{s.label}</button>
          ))}
        </div>
      )}

      <div className="bot-input">
        <input placeholder="Or type it your way…" />
        <button onClick={restart}>Reset</button>
      </div>
    </div>
  );
}

Object.assign(window, { Chatbot });
