// E28E Assistant — interactive chat scoped by role
const SUGGESTIONS = {
  owner: [
    "What needs my attention today?",
    "Show me overdue invoices",
    "How are we tracking against May goal?",
    "Draft a thank-you note to Diane",
  ],
  employee: [
    "What's on my schedule today?",
    "Mark Mt. Tabor walk-through done",
    "Check inventory for cedar mulch",
    "Message Elena about the Cedar Hill plants",
  ],
};

// Pre-canned responses so the chat feels real without an LLM call.
const responses = {
  owner: {
    "what needs my attention today?": {
      reply: "Three things stand out for today:",
      card: {
        title: "Priority queue",
        rows: [
          ["Diane Kapoor — deposit pending", "$8,400"],
          ["Cedar mulch low — auto-reorder ready", "Approve"],
          ["Mt. Tabor 92% — schedule final walk-through", "Today"],
        ],
      },
      followups: ["Approve mulch reorder", "Open Diane's file", "Message the crew"],
    },
    "show me overdue invoices": {
      reply: "You have one overdue invoice — $2,300, 8 days past due.",
      card: {
        title: "Overdue · 1",
        rows: [["Hawthorne café — Inv. #1182", "$2,300 · 8d"]],
      },
      followups: ["Send a polite reminder", "Call the customer", "Mark as paid"],
    },
    "how are we tracking against may goal?": {
      reply: "You're at $84.2k of the $110k May goal — 76% with 25 days remaining. Pace is +12% vs. last May.",
      followups: ["Forecast end of month", "Compare to April", "What's driving growth?"],
    },
  },
  employee: {
    "what's on my schedule today?": {
      reply: "You have three site stops and one call:",
      card: {
        title: "Wed, May 6",
        rows: [
          ["8:30 — Crew dispatch · Cedar Hill", "On site"],
          ["12:30 — Salem Stone pickup", "Errand"],
          ["15:00 — Sellwood site walk", "On site"],
        ],
      },
      followups: ["Get directions to Cedar Hill", "Who's on my crew?", "Log my hours"],
    },
    "check inventory for cedar mulch": {
      reply: "Cedar mulch is low — 2 of 8 cu yd. The reorder draft is waiting on Anya's approval.",
      followups: ["Ping Anya", "Substitute with fir bark?", "Call Salem Stone"],
    },
  },
};

const fallback = (role) => ({
  reply:
    role === "owner"
      ? "I'd pull that together from your finances, projects and inbox. Want me to draft a summary?"
      : "Let me check your tasks and projects for that. Want me to assign it to Elena?",
  followups: SUGGESTIONS[role].slice(0, 3),
});

const Assistant = ({ role, brand, onClose, onAction }) => {
  const [messages, setMessages] = React.useState(() => []);
  const [text, setText] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const chatRef = React.useRef(null);

  const send = (raw) => {
    const q = (raw ?? text).trim();
    if (!q) return;
    setMessages((m) => [...m, { from: "user", text: q }]);
    setText("");
    setTyping(true);
    setTimeout(() => {
      const key = q.toLowerCase();
      const resp = responses[role][key] || fallback(role);
      setTyping(false);
      setMessages((m) => [...m, { from: "bot", text: resp.reply, card: resp.card, followups: resp.followups }]);
    }, 700 + Math.random() * 400);
  };

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

  return (
    <aside className="assistant-drawer">
      <div className="assistant-head">
        <div className="assistant-mark" style={{ background: "var(--accent)", color: "var(--accent-ink)" }}>e</div>
        <div>
          <div className="assistant-title">E28E Assistant</div>
          <div className="assistant-sub">
            <span className="scope-chip"><span className="dot" /> {role === "owner" ? "Full access" : "Scoped: Crew Lead"}</span>
          </div>
        </div>
        <button className="icon-btn assistant-close" onClick={onClose} title="Close">
          <Ic.Close size={13} />
        </button>
      </div>

      <div className="composer composer-top">
        <div className="composer-box">
          <textarea
            placeholder={role === "owner" ? "Ask about finances, projects, customers…" : "Ask about your tasks, schedule, materials…"}
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }
            }}
            rows={1}
          />
          <button className="composer-send" disabled={!text.trim()} onClick={() => send()}>
            <Ic.Send size={13} />
          </button>
        </div>
        <div className="composer-foot">
          <span className="scope-chip"><span className="dot" /> Scope: {role === "owner" ? "Full business" : "Crew Lead — tasks & projects"}</span>
          <span style={{ marginLeft: "auto" }}>⏎ to send</span>
        </div>
        <div className="assistant-reassure">
          <Ic.Undo size={11} /> Nothing sends without your yes — review and undo anything.
        </div>
      </div>

      {messages.length === 0 && (
        <div className="suggested suggested-below">
          {SUGGESTIONS[role].map((s, i) => (
            <button key={i} className="suggest" onClick={() => send(s)}>
              <Ic.Sparkle size={11} /> {s}
            </button>
          ))}
        </div>
      )}

      <div className="chat" ref={chatRef} data-empty={messages.length === 0 ? "true" : "false"}>
        {messages.map((m, i) => (
          <div key={i} className={`msg ${m.from}`}>
            {m.from === "bot" && <div className="msg-meta">E28E</div>}
            <div className="bubble">{m.text}</div>
            {m.card && (
              <div className="msg-card">
                <div className="msg-card-head">{m.card.title}</div>
                <div className="msg-card-body">
                  {m.card.rows.map((r, j) => (
                    <div key={j} className="msg-card-row">
                      <span className="l">{r[0]}</span>
                      <span>{r[1]}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
            {m.followups && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
                {m.followups.map((f, j) => (
                  <button key={j} className="suggest" onClick={() => send(f)}>{f}</button>
                ))}
              </div>
            )}
          </div>
        ))}
        {typing && (
          <div className="msg bot">
            <div className="msg-meta">E28E</div>
            <div className="typing"><span /><span /><span /></div>
          </div>
        )}
      </div>
    </aside>
  );
};

window.Assistant = Assistant;
