/* global React, Icon, Avatar, Modal, Field, TextInput, TextArea, SelectInput, BookCover, searchGoogleBooks */
const { useState, useEffect, useRef } = React;

/* ============================================
   CHAT HUB — pick an agent
   ============================================ */
function ChatHubScreen({ state, actions }) {
  const agents = window.LIBRARY_DATA.AGENTS;
  return (
    <div className="col gap-6">
      <div>
        <h1 className="screen-title">שיחה</h1>
        <div className="screen-sub">בחרי עם מי לדבר על הספרייה</div>
      </div>

      <div className="col gap-3">
        {agents.map(a => (
          <button
            key={a.id}
            className="card row gap-4"
            onClick={() => actions.openChat(a.id)}
            style={{
              cursor: "pointer",
              alignItems: "center",
              textAlign: "start",
              padding: 22,
              borderRight: `4px solid ${a.accent}`,
              borderRadius: "var(--radius-lg)",
            }}
          >
            <div style={{
              width: 64, height: 64,
              borderRadius: 18,
              background: `linear-gradient(140deg, ${a.accent}, ${shade(a.accent, -20)})`,
              display: "grid", placeItems: "center",
              fontSize: 32,
              boxShadow: "0 6px 16px -8px rgba(0,0,0,.3)",
            }}>{a.emoji}</div>
            <div className="col grow">
              <div className="serif" style={{ fontSize: 22, fontWeight: 700 }}>{a.name}</div>
              <div className="muted" style={{ fontSize: 14 }}>{a.role}</div>
              <div className="row gap-2 mt-3" style={{ flexWrap: "wrap" }}>
                {a.prompts.slice(0, 2).map(p => <span key={p} className="chip" style={{ fontSize: 12 }}>"{p}"</span>)}
              </div>
            </div>
            <Icon name="forward" size={20} style={{ color: "var(--ink-mute)", transform: "scaleX(-1)" }} />
          </button>
        ))}
      </div>

      <div className="card" style={{
        background: "linear-gradient(135deg, rgba(180,138,58,.08), rgba(180,138,58,.02))",
        borderColor: "rgba(180,138,58,.25)",
      }}>
        <div className="row gap-3" style={{ alignItems: "center" }}>
          <span style={{ color: "var(--gold)" }}><Icon name="sparkle" size={20} /></span>
          <div className="serif" style={{ fontSize: 17, fontWeight: 700 }}>שיחה חכמה</div>
        </div>
        <div className="muted mt-2" style={{ fontSize: 14, lineHeight: 1.6 }}>
          כל אחת מהדמויות מכירה את הספרייה שלך, יודעת מה שאלת ממי, ומה את בקריאה. אפשר לדבר על ספרים, להמליץ, או רק לשמוע סיפור.
        </div>
      </div>
    </div>
  );
}

/* ============================================
   CHAT ROOM
   ============================================ */
function ChatScreen({ agentId, state, actions, onBack }) {
  const agent = window.LIBRARY_DATA.AGENTS.find(a => a.id === agentId);
  const [messages, setMessages] = useState([
    { from: "agent", text: agent.greeting, ts: Date.now() },
  ]);
  const [draft, setDraft] = useState("");
  const [typing, setTyping] = useState(false);
  const endRef = useRef(null);

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" }); }, [messages, typing]);

  const send = (text) => {
    const t = (text || draft).trim();
    if (!t) return;
    setMessages(m => [...m, { from: "user", text: t, ts: Date.now() }]);
    setDraft("");
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMessages(m => [...m, { from: "agent", text: respond(agent, t, state), ts: Date.now() }]);
    }, 900 + Math.random() * 700);
  };

  return (
    <div className="col" style={{ minHeight: "calc(100vh - 180px)" }}>
      <div className="row between" style={{ marginBottom: 24 }}>
        <button className="btn btn-icon btn-ghost" onClick={onBack}><Icon name="back" size={20} /></button>
        <div className="row gap-3" style={{ alignItems: "center" }}>
          <div style={{
            width: 44, height: 44,
            borderRadius: 12,
            background: `linear-gradient(140deg, ${agent.accent}, ${shade(agent.accent, -20)})`,
            display: "grid", placeItems: "center",
            fontSize: 22,
          }}>{agent.emoji}</div>
          <div>
            <div className="serif" style={{ fontSize: 20, fontWeight: 700, lineHeight: 1 }}>{agent.name}</div>
            <div className="muted" style={{ fontSize: 12 }}>{agent.role}</div>
          </div>
        </div>
        <button className="btn btn-icon btn-ghost" title="נקה שיחה" onClick={() => setMessages([{ from: "agent", text: agent.greeting, ts: Date.now() }])}>
          <Icon name="trash" size={18} />
        </button>
      </div>

      <div className="col gap-3 grow" style={{ overflow: "auto", paddingBottom: 12 }}>
        {messages.map((m, i) => (
          <div key={i} className="row gap-2" style={{ flexDirection: m.from === "agent" ? "row" : "row-reverse", alignItems: "flex-end" }}>
            {m.from === "agent" && (
              <div style={{ width: 28, height: 28, borderRadius: 8, background: agent.accent, display: "grid", placeItems: "center", fontSize: 14, flexShrink: 0 }}>{agent.emoji}</div>
            )}
            <div className={`chat-msg ${m.from === "agent" ? "from-agent" : "from-user"}`}>{m.text}</div>
          </div>
        ))}
        {typing && (
          <div className="row gap-2" style={{ alignItems: "flex-end" }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: agent.accent, display: "grid", placeItems: "center", fontSize: 14 }}>{agent.emoji}</div>
            <div className="chat-msg from-agent"><Dots /></div>
          </div>
        )}
        <div ref={endRef}></div>
      </div>

      <div className="col gap-3" style={{ marginTop: "auto", paddingTop: 12 }}>
        <div className="row gap-2" style={{ flexWrap: "wrap", justifyContent: "flex-end" }}>
          {agent.prompts.map(p => (
            <button key={p} className="chip" onClick={() => send(p)}>{p}</button>
          ))}
        </div>
        <div className="row gap-2" style={{ alignItems: "center" }}>
          <button className="btn btn-icon btn-ghost"><Icon name="mic" size={18} /></button>
          <input
            className="input"
            placeholder="כתבי הודעה…"
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onKeyDown={e => e.key === "Enter" && send()}
          />
          <button className="btn btn-icon btn-primary" onClick={() => send()}><Icon name="send" size={16} /></button>
        </div>
      </div>
    </div>
  );
}

const Dots = () => (
  <span style={{ display: "inline-flex", gap: 3, padding: "4px 2px" }}>
    {[0, 1, 2].map(i => (
      <span key={i} style={{
        width: 6, height: 6, borderRadius: "50%",
        background: "var(--ink-mute)",
        animation: `bounce 1.2s ease-in-out ${i * .15}s infinite`,
      }}></span>
    ))}
    <style>{`@keyframes bounce { 0%, 60%, 100% { transform: translateY(0); opacity: .5 } 30% { transform: translateY(-4px); opacity: 1 } }`}</style>
  </span>
);

function respond(agent, text, state) {
  const { books, loans } = state;
  const t = text.toLowerCase();
  if (agent.id === "curator") {
    if (t.includes("כמה") || t.includes("ספרים")) {
      return `יש לך ${books.length} ספרים בספרייה. ${books.filter(b=>b.status==="available").length} זמינים, ${books.filter(b=>b.status==="loaned").length} מושאלים, ו־${books.filter(b=>b.status==="reading").length} בקריאה כרגע.`;
    }
    if (t.includes("סוס")) {
      const loan = loans.find(l => l.bookId === "b1");
      return loan ? `"סוס אחד נכנס לבר" נמצא כרגע אצל ${loan.borrower}.` : "הספר נמצא במדף.";
    }
    if (t.includes("קריאה") || t.includes("בקריאה")) {
      const r = books.filter(b => b.status === "reading");
      return r.length ? `את קוראת כרגע: ${r.map(b => `"${b.title}"`).join(", ")}.` : "אין כרגע ספרים בקריאה.";
    }
    return "אני יכול לעזור עם קטלוג הספרייה — כמה ספרים, מי מחזיק מה, מה במצב קריאה.";
  }
  if (agent.id === "librarian") {
    if (t.includes("השאל")) return "בשמחה! מי לוקח, איזה ספר, ועד מתי?";
    if (t.includes("איחור")) {
      const late = loans.filter(l => new Date(l.dueAt) < new Date());
      return late.length ? `יש ${late.length} השאלות באיחור.` : "הכל בזמן 🎉";
    }
    if (t.includes("תזכ")) return "שלחתי תזכורת.";
    return "אני אטפל בכל מה שקשור להשאלות.";
  }
  if (agent.id === "advisor") {
    if (t.includes("המלץ") || t.includes("ספר")) {
      const cand = books.find(b => b.status === "available" && b.rating === 0);
      return cand ? `על סמך מה שאת אוהבת, אני חושבת ש"${cand.title}" יתאים לך.` : "תני לי כיוון — אווירה, ז'אנר, או ספר אהוב.";
    }
    return "ספרי לי מה את בקריאה. אני מקשיבה.";
  }
}

function shade(hex, percent) {
  const num = parseInt(hex.slice(1), 16);
  const amt = Math.round(2.55 * percent);
  const r = Math.max(0, Math.min(255, (num >> 16) + amt));
  const g = Math.max(0, Math.min(255, ((num >> 8) & 0xff) + amt));
  const b = Math.max(0, Math.min(255, (num & 0xff) + amt));
  return `rgb(${r}, ${g}, ${b})`;
}

/* ============================================
   ADD BOOK MODAL — with Google Books cover search
   ============================================ */
function AddBookModal({ open, onClose, onAdd }) {
  const EMPTY = { title: "", author: "", genre: "פרוזה", pages: "", year: "", notes: "", coverUrl: "" };
  const [f, setF] = useState(EMPTY);
  const [coverResults, setCoverResults] = useState([]);
  const [coverLoading, setCoverLoading] = useState(false);
  const debounceRef = useRef(null);

  useEffect(() => {
    if (!open) { setF(EMPTY); setCoverResults([]); }
  }, [open]);

  const set = (k) => (e) => {
    const val = e.target.value;
    setF(prev => ({ ...prev, [k]: val }));
    if (k === "title") {
      clearTimeout(debounceRef.current);
      if (val.length >= 2) {
        debounceRef.current = setTimeout(async () => {
          setCoverLoading(true);
          const results = await searchGoogleBooks(val, f.author);
          setCoverResults(results);
          if (results.length > 0 && !f.coverUrl) {
            setF(prev => ({ ...prev, coverUrl: results[0].coverUrl }));
          }
          setCoverLoading(false);
        }, 600);
      } else {
        setCoverResults([]);
      }
    }
  };

  if (!open) return null;

  const submit = () => {
    if (!f.title.trim()) return;
    onAdd(f);
    setF(EMPTY);
    setCoverResults([]);
    onClose();
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="ספר חדש"
      sub="הוספה לקטלוג הספרייה"
      wide
      footer={
        <>
          <button className="btn btn-primary" onClick={submit}><Icon name="plus" size={16} /> הוסיפי לספרייה</button>
          <button className="btn btn-ghost" onClick={onClose}>ביטול</button>
        </>
      }
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Field label="שם הספר *">
          <TextInput value={f.title} onChange={set("title")} placeholder="למשל: סוס אחד נכנס לבר" autoFocus />
        </Field>
        <Field label="סופר/ת">
          <TextInput value={f.author} onChange={set("author")} placeholder="דויד גרוסמן" />
        </Field>
        <Field label="ז'אנר">
          <SelectInput value={f.genre} onChange={set("genre")} options={["פרוזה", "שירה", "עיון", "מסות", "ילדים", "אחר"]} />
        </Field>
        <Field label="שנת הוצאה">
          <TextInput type="number" value={f.year} onChange={set("year")} placeholder="2024" />
        </Field>
        <Field label="מספר עמודים">
          <TextInput type="number" value={f.pages} onChange={set("pages")} placeholder="240" />
        </Field>
        <Field label="קישור כריכה (אופציונלי)">
          <TextInput value={f.coverUrl} onChange={set("coverUrl")} placeholder="יובא אוטומטית מגוגל" />
        </Field>
      </div>

      {/* Cover picker */}
      {(coverLoading || coverResults.length > 0) && (
        <div className="mt-4">
          <div className="field-label" style={{ marginBottom: 8 }}>
            {coverLoading ? "מחפש כריכות…" : "בחרי כריכה:"}
          </div>
          <div className="row gap-3" style={{ flexWrap: "wrap" }}>
            {coverResults.map((r, i) => (
              <div
                key={i}
                onClick={() => setF(prev => ({ ...prev, coverUrl: r.coverUrl }))}
                style={{
                  cursor: "pointer",
                  borderRadius: 8,
                  overflow: "hidden",
                  border: f.coverUrl === r.coverUrl ? "3px solid var(--gold)" : "3px solid transparent",
                  boxShadow: f.coverUrl === r.coverUrl ? "0 0 0 2px var(--gold)" : "0 2px 8px rgba(0,0,0,.15)",
                  flexShrink: 0,
                }}
                title={r.title}
              >
                <img src={r.coverUrl} alt={r.title} style={{ width: 60, height: 88, objectFit: "cover", display: "block" }} />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Preview selected cover */}
      {f.coverUrl && coverResults.length === 0 && (
        <div className="mt-4 row gap-3" style={{ alignItems: "center" }}>
          <img src={f.coverUrl} alt="כריכה" style={{ width: 60, height: 88, objectFit: "cover", borderRadius: 6 }} onError={() => setF(prev => ({ ...prev, coverUrl: "" }))} />
          <div className="muted" style={{ fontSize: 13 }}>כריכה נבחרה</div>
        </div>
      )}

      <Field label="הערות אישיות">
        <TextArea value={f.notes} onChange={set("notes")} placeholder="מאיפה הגיע, למה אהבת, מה רצית לזכור..." />
      </Field>
    </Modal>
  );
}

/* ============================================
   CREATE LOAN MODAL
   ============================================ */
function CreateLoanModal({ open, onClose, books, preselectedBookId, onAdd }) {
  const [f, setF] = useState({ bookId: preselectedBookId || "", borrower: "", dueAt: "", note: "" });
  useEffect(() => { if (preselectedBookId) setF(x => ({ ...x, bookId: preselectedBookId })); }, [preselectedBookId]);
  if (!open) return null;
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const submit = () => {
    if (!f.bookId || !f.borrower.trim()) return;
    onAdd(f);
    setF({ bookId: "", borrower: "", dueAt: "", note: "" });
    onClose();
  };
  const available = books.filter(b => b.status === "available" || b.id === preselectedBookId);
  return (
    <Modal
      open={open}
      onClose={onClose}
      title="השאלה חדשה"
      sub="מי לוקח את הספר ולכמה זמן?"
      footer={
        <>
          <button className="btn btn-primary" onClick={submit}><Icon name="handoff" size={16} /> צרי השאלה</button>
          <button className="btn btn-ghost" onClick={onClose}>ביטול</button>
        </>
      }
    >
      <Field label="איזה ספר?">
        <SelectInput value={f.bookId} onChange={set("bookId")} options={[
          { value: "", label: "בחרי ספר…" },
          ...available.map(b => ({ value: b.id, label: `${b.title} — ${b.author}` })),
        ]} />
      </Field>
      <Field label="מי לוקח?">
        <TextInput value={f.borrower} onChange={set("borrower")} placeholder="שם החבר/ה" />
      </Field>
      <Field label="להחזיר עד">
        <TextInput type="date" value={f.dueAt} onChange={set("dueAt")} />
      </Field>
      <Field label="הערה (אופציונלי)">
        <TextArea value={f.note} onChange={set("note")} placeholder="הקשר, מה הוא מחפש..." />
      </Field>
    </Modal>
  );
}

/* ============================================
   ADD WISH MODAL
   ============================================ */
function AddWishModal({ open, onClose, onAdd }) {
  const [f, setF] = useState({ title: "", author: "", reason: "", priority: "med" });
  if (!open) return null;
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const submit = () => {
    if (!f.title.trim()) return;
    onAdd(f);
    setF({ title: "", author: "", reason: "", priority: "med" });
    onClose();
  };
  return (
    <Modal
      open={open}
      onClose={onClose}
      title="משאלה חדשה"
      sub="ספר שאת רוצה לקרוא יום אחד"
      footer={
        <>
          <button className="btn btn-primary" onClick={submit}><Icon name="heart" size={16} /> הוסיפי משאלה</button>
          <button className="btn btn-ghost" onClick={onClose}>ביטול</button>
        </>
      }
    >
      <Field label="שם הספר *">
        <TextInput value={f.title} onChange={set("title")} placeholder="ספר שתפסת ממישהו..." autoFocus />
      </Field>
      <Field label="סופר/ת">
        <TextInput value={f.author} onChange={set("author")} />
      </Field>
      <Field label="למה את רוצה אותו?">
        <TextArea value={f.reason} onChange={set("reason")} placeholder="המלצה של מישהו, פודקאסט, סיקור..." />
      </Field>
      <Field label="דחיפות">
        <div className="row gap-2 mt-2">
          {[
            { id: "high", label: "דחוף", c: "var(--rust)" },
            { id: "med", label: "בקרוב", c: "var(--gold)" },
            { id: "low", label: "יום אחד", c: "var(--ink-mute)" },
          ].map(p => (
            <button
              key={p.id}
              className="chip"
              onClick={() => setF({ ...f, priority: p.id })}
              style={{
                background: f.priority === p.id ? p.c : "var(--paper-card)",
                color: f.priority === p.id ? "#fff8e8" : "var(--ink)",
                borderColor: f.priority === p.id ? p.c : "var(--line-strong)",
              }}
            >{p.label}</button>
          ))}
        </div>
      </Field>
    </Modal>
  );
}

Object.assign(window, { ChatHubScreen, ChatScreen, AddBookModal, CreateLoanModal, AddWishModal });
