/* global React, Icon, BookCover, BookSpine, StatusPill, Stars, Avatar, Modal, Field, TextInput, TextArea, SelectInput, Segment, Empty, searchGoogleBooks */
const { useState, useRef } = React;

function HomeScreen({ state, actions }) {
  const { books, loans, wishes, activity } = state;
  const counts = {
    all: books.length,
    available: books.filter(b => b.status === "available").length,
    reading: books.filter(b => b.status === "reading").length,
    loaned: books.filter(b => b.status === "loaned").length,
  };
  const recent = [...books].sort((a, b) => b.addedAt.localeCompare(a.addedAt)).slice(0, 6);
  const dueSoon = loans
    .map(l => ({ ...l, book: books.find(b => b.id === l.bookId), days: daysBetween(l.dueAt) }))
    .sort((a, b) => a.days - b.days);

  return (
    <div className="col gap-6">
      <div className="row between" style={{ alignItems: "flex-end", flexWrap: "wrap", gap: 24 }}>
        <div>
          <div className="muted" style={{ fontSize: 13, letterSpacing: ".06em" }}>שלום מאי 👋</div>
          <h1 className="screen-title mt-2">הספרייה הפרטית שלי</h1>
          <div className="screen-sub">{counts.all} ספרים · {counts.available} זמינים · {counts.loaned} מושאלים · {counts.reading} בקריאה</div>
        </div>
        <div className="row gap-3">
          <button className="btn" onClick={() => actions.openAddWish()}><Icon name="heart" size={16} />משאלה</button>
          <button className="btn btn-primary" onClick={() => actions.openAddBook()}><Icon name="plus" size={16} />ספר חדש</button>
        </div>
      </div>

      <div className="card" style={{ padding: 18 }}>
        <div className="search">
          <span className="search-icon"><Icon name="search" size={18} /></span>
          <input className="input" placeholder="חיפוש לפי שם ספר, מחבר, ז'אנר…" onChange={e => actions.setQuery(e.target.value)} />
        </div>
        <div className="row gap-3 mt-3" style={{ flexWrap: "wrap" }}>
          {[["tag","ז'אנר"],["user","מחבר"],["calendar","תאריך"],["star","מדורגים"]].map(([ic,lb]) => (
            <button key={lb} className="chip"><Icon name={ic} size={13} /> {lb}</button>
          ))}
        </div>
      </div>

      <div className="stat-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))", gap: 14 }}>
        <Stat icon="book"     num={counts.all}      label="ספרים בסך הכל"   trend="+2 החודש" />
        <Stat icon="check"    num={counts.available} label="זמינים" />
        <Stat icon="handoff"  num={counts.loaned}    label="מושאלים"         trend={dueSoon[0] ? `קרוב: ${dueSoon[0].days} ימים` : null} />
        <Stat icon="openbook" num={counts.reading}   label="בקריאה כרגע" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }} className="responsive-2col">
        <div className="card">
          <div className="row between mt-2">
            <div className="serif" style={{ fontSize: 22, fontWeight: 700 }}>הוספתי לאחרונה</div>
            <button className="btn btn-ghost btn-sm" onClick={() => actions.go("library")}>הכל ←</button>
          </div>
          <div className="row gap-3 mt-4" style={{ overflowX: "auto", paddingBottom: 8 }}>
            {recent.map(b => (
              <div key={b.id} onClick={() => actions.openBook(b.id)} style={{ flex: "0 0 auto", textAlign: "center", cursor: "pointer" }}>
                <BookCover book={b} width={90} height={130} />
                <div className="serif mt-2" style={{ fontSize: 13, fontWeight: 700, maxWidth: 90, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.title}</div>
                <div className="muted" style={{ fontSize: 11 }}>{b.author}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="row between">
            <div className="serif" style={{ fontSize: 22, fontWeight: 700 }}>החזרות צפויות</div>
            <button className="btn btn-ghost btn-sm" onClick={() => actions.go("loans")}>הכל ←</button>
          </div>
          {dueSoon.length === 0 ? (
            <div className="muted mt-4" style={{ fontSize: 13 }}>אין השאלות פעילות 🎉</div>
          ) : (
            <div className="col gap-3 mt-4">
              {dueSoon.map(l => (
                <div key={l.id} className="row gap-3" style={{ alignItems: "center" }}>
                  <Avatar name={l.borrower} />
                  <div className="col grow" style={{ minWidth: 0 }}>
                    <div className="serif" style={{ fontWeight: 700, fontSize: 14 }}>{l.book?.title}</div>
                    <div className="muted" style={{ fontSize: 12 }}>אצל {l.borrower}</div>
                  </div>
                  <div style={{ textAlign: "end" }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: l.days < 7 ? "var(--rust)" : "var(--ink)" }}>
                      {l.days < 0 ? `איחור ${-l.days} ימים` : l.days === 0 ? "היום" : `בעוד ${l.days} ימים`}
                    </div>
                    <button className="btn btn-sm btn-ghost" onClick={() => actions.remindLoan(l.id)}>תזכרי</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="card">
        <div className="serif" style={{ fontSize: 22, fontWeight: 700 }}>פעילות אחרונה</div>
        <div className="col gap-3 mt-4">
          {activity.slice(0, 4).map(a => (
            <div key={a.id} className="row gap-3" style={{ alignItems: "center" }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, display: "grid", placeItems: "center", background: "rgba(180,138,58,.12)", color: "var(--gold)" }}>
                <Icon name={a.type === "loan" ? "handoff" : a.type === "wish" ? "heart" : a.type === "rate" ? "star" : a.type === "return" ? "check" : "plus"} size={14} />
              </span>
              <div className="grow">{a.text}</div>
              <div className="muted" style={{ fontSize: 12 }}>{formatDate(a.date)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const Stat = ({ icon, num, label, trend }) => (
  <div className="stat">
    <span className="stat-icon"><Icon name={icon} size={18} /></span>
    <div className="stat-num">{num}</div>
    <div className="stat-label">{label}</div>
    {trend && <div className="stat-trend">{trend}</div>}
  </div>
);

function LibraryScreen({ state, actions }) {
  const { books } = state;
  const [view, setView] = useState("shelf");
  const [status, setStatus] = useState("all");
  const [genre, setGenre] = useState("הכל");
  const [q, setQ] = useState("");

  const filtered = books.filter(b => {
    if (status !== "all" && b.status !== status) return false;
    if (genre !== "הכל" && b.genre !== genre) return false;
    if (q && !`${b.title} ${b.author} ${b.tags.join(" ")}`.includes(q)) return false;
    return true;
  });

  const statusItems = [
    { id: "all", label: "הכל", count: books.length },
    { id: "available", label: "זמין", count: books.filter(b => b.status === "available").length },
    { id: "reading", label: "בקריאה", count: books.filter(b => b.status === "reading").length },
    { id: "loaned", label: "מושאל", count: books.filter(b => b.status === "loaned").length },
  ];

  return (
    <div className="col gap-6">
      <div className="row between" style={{ alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
        <div>
          <h1 className="screen-title">הספרייה</h1>
          <div className="screen-sub">{filtered.length} ספרים · ממוינים לפי הוספה אחרונה</div>
        </div>
        <div className="row gap-3">
          <Segment items={[{ id:"shelf",label:"מדף"},{ id:"grid",label:"כריכות"},{ id:"list",label:"רשימה"}]} value={view} onChange={setView} />
          <button className="btn btn-primary" onClick={() => actions.openAddBook()}><Icon name="plus" size={16} /> ספר חדש</button>
        </div>
      </div>

      <div className="card" style={{ padding: 18 }}>
        <div className="search">
          <span className="search-icon"><Icon name="search" size={18} /></span>
          <input className="input" placeholder="חיפוש לפי שם / סופר / הערות…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div className="row gap-3 mt-3" style={{ flexWrap: "wrap", alignItems: "center" }}>
          <Segment items={statusItems} value={status} onChange={setStatus} />
          <div style={{ flex: 1 }}></div>
          <div className="row gap-2" style={{ flexWrap: "wrap" }}>
            {window.LIBRARY_DATA.GENRES.map(g => (
              <button key={g} className="chip" onClick={() => setGenre(g)}
                style={{ background: genre===g?"var(--walnut-3)":"var(--paper-card)", color: genre===g?"var(--gold-soft)":"var(--ink)", borderColor: genre===g?"var(--walnut)":"var(--line-strong)" }}>
                {g}
              </button>
            ))}
          </div>
        </div>
      </div>

      {filtered.length === 0 ? (
        <Empty icon="search" title="אין תוצאות" sub="נסי לשנות את הסינון, או הוסיפי ספר חדש"
          action={<button className="btn btn-primary" onClick={() => actions.openAddBook()}><Icon name="plus" size={16} /> ספר חדש</button>} />
      ) : view === "shelf" ? <ShelfView books={filtered} onSelect={actions.openBook} />
        : view === "grid"  ? <GridView  books={filtered} onSelect={actions.openBook} />
        : <ListView books={filtered} onSelect={actions.openBook} />}
    </div>
  );
}

const ShelfView = ({ books, onSelect }) => {
  const shelves = [];
  for (let i = 0; i < books.length; i += 10) shelves.push(books.slice(i, i + 10));
  return (
    <div className="col gap-6">
      {shelves.map((row, i) => (
        <div key={i} className="shelf">
          {row.map(b => <BookSpine key={b.id} book={b} onClick={() => onSelect(b.id)} />)}
        </div>
      ))}
    </div>
  );
};

const GridView = ({ books, onSelect }) => (
  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 18 }}>
    {books.map(b => (
      <div key={b.id} className="col gap-2" style={{ cursor: "pointer" }} onClick={() => onSelect(b.id)}>
        <BookCover book={b} width={140} height={200} />
        <div className="row between mt-2" style={{ alignItems: "flex-start" }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div className="serif" style={{ fontSize: 15, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{b.title}</div>
            <div className="muted" style={{ fontSize: 12 }}>{b.author}</div>
          </div>
        </div>
        <StatusPill status={b.status} />
      </div>
    ))}
  </div>
);

const ListView = ({ books, onSelect }) => (
  <div className="card" style={{ padding: 0, overflow: "hidden" }}>
    {books.map((b, i) => (
      <div key={b.id} className="row gap-4" onClick={() => onSelect(b.id)}
        style={{ padding: "14px 18px", borderTop: i > 0 ? "1px solid var(--line)" : "none", cursor: "pointer", alignItems: "center" }}>
        <BookCover book={b} width={42} height={62} />
        <div className="col grow" style={{ minWidth: 0 }}>
          <div className="serif" style={{ fontSize: 16, fontWeight: 700 }}>{b.title}</div>
          <div className="muted" style={{ fontSize: 13 }}>{b.author} · {b.year} · {b.pages} עמ'</div>
        </div>
        <Stars value={b.rating} />
        <StatusPill status={b.status} />
      </div>
    ))}
  </div>
);

/* ── Book Sheet ── */
function BookSheet({ book, state, actions, onClose }) {
  if (!book) return null;
  const loan = state.loans.find(l => l.bookId === book.id);
  const [fetchingCover, setFetchingCover] = useState(false);
  const [coverSuggestions, setCoverSuggestions] = useState([]);

  const fetchCover = async () => {
    setFetchingCover(true);
    const results = await searchGoogleBooks(book.title, book.author);
    setCoverSuggestions(results);
    setFetchingCover(false);
  };

  return (
    <>
      <div className="sheet-back" onClick={onClose}></div>
      <div className="sheet">
        <div className="row between">
          <button className="btn btn-icon btn-ghost" onClick={onClose}><Icon name="back" size={20} /></button>
          <div className="row gap-2">
            <button className="btn btn-icon btn-ghost"><Icon name="bookmark" size={18} /></button>
            <button className="btn btn-icon btn-ghost"><Icon name="edit" size={18} /></button>
            <button className="btn btn-icon btn-ghost"><Icon name="more" size={18} /></button>
          </div>
        </div>

        <div className="row gap-4 mt-6" style={{ alignItems: "flex-end" }}>
          <div className="col gap-2">
            <BookCover book={book} width={140} height={210} />
            {!book.coverUrl && (
              <button className="btn btn-sm btn-ghost" onClick={fetchCover} style={{ fontSize: 11 }}>
                {fetchingCover ? "מחפש…" : <><Icon name="image" size={12} /> כריכה מגוגל</>}
              </button>
            )}
          </div>
          <div className="col grow">
            <StatusPill status={book.status} />
            <h2 className="serif mt-2" style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-.02em", lineHeight: 1.1, margin: 0 }}>{book.title}</h2>
            <div className="muted mt-2" style={{ fontSize: 15 }}>{book.author}</div>
            <div className="row gap-3 mt-3" style={{ fontSize: 12, color: "var(--ink-mute)" }}>
              <span>{book.year}</span><span>·</span><span>{book.pages} עמ'</span><span>·</span><span>{book.genre}</span>
            </div>
            <div className="mt-3"><Stars value={book.rating} size={18} /></div>
          </div>
        </div>

        {coverSuggestions.length > 0 && (
          <div className="mt-4">
            <div className="muted" style={{ fontSize: 12, fontWeight: 600, marginBottom: 8 }}>בחרי כריכה:</div>
            <div className="row gap-2" style={{ flexWrap: "wrap" }}>
              {coverSuggestions.map((s, i) => (
                <img key={i} src={s.coverUrl} alt={s.title}
                  style={{ width: 56, height: 84, objectFit: "cover", borderRadius: 4, cursor: "pointer", border: "2px solid transparent", transition: "border .15s" }}
                  onClick={() => { actions.setCover(book.id, s.coverUrl); setCoverSuggestions([]); }}
                  onMouseOver={e => e.target.style.borderColor = "var(--gold)"}
                  onMouseOut={e => e.target.style.borderColor = "transparent"}
                />
              ))}
              <button className="chip btn-sm" onClick={() => setCoverSuggestions([])}>סגרי</button>
            </div>
          </div>
        )}

        {book.progress > 0 && book.progress < 1 && (
          <div className="mt-6">
            <div className="row between mt-2" style={{ fontSize: 13 }}>
              <span className="muted">התקדמות</span>
              <span style={{ fontWeight: 700 }}>{Math.round(book.progress * 100)}%</span>
            </div>
            <div className="progress mt-2"><span style={{ width: `${book.progress * 100}%` }}></span></div>
          </div>
        )}

        <div className="row gap-3 mt-6" style={{ flexWrap: "wrap" }}>
          {book.status === "available" && (
            <>
              <button className="btn btn-primary" onClick={() => actions.openCreateLoan(book.id)}><Icon name="handoff" size={16} /> השאילי</button>
              <button className="btn" onClick={() => actions.startReading(book.id)}><Icon name="openbook" size={16} /> התחילי לקרוא</button>
            </>
          )}
          {book.status === "reading" && (
            <button className="btn btn-primary" onClick={() => actions.markFinished(book.id)}><Icon name="check" size={16} /> סיימתי</button>
          )}
          {book.status === "loaned" && loan && (
            <>
              <div className="card card-tight row gap-3" style={{ alignItems: "center", flex: 1 }}>
                <Avatar name={loan.borrower} />
                <div className="col grow">
                  <div style={{ fontWeight: 700, fontSize: 13 }}>אצל {loan.borrower}</div>
                  <div className="muted" style={{ fontSize: 12 }}>הוחזר עד {formatDate(loan.dueAt)}</div>
                </div>
              </div>
              <button className="btn btn-primary" onClick={() => actions.returnLoan(loan.id)}><Icon name="check" size={16} /> חזר</button>
            </>
          )}
        </div>

        {book.tags.length > 0 && (
          <div className="mt-6">
            <div className="muted" style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".06em" }}>תגיות</div>
            <div className="row gap-2 mt-2" style={{ flexWrap: "wrap" }}>
              {book.tags.map(t => <span key={t} className="chip">{t}</span>)}
            </div>
          </div>
        )}

        {book.notes && (
          <div className="mt-6">
            <div className="muted" style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".06em" }}>ההערות שלי</div>
            <div className="card mt-2" style={{ padding: 16, background: "rgba(180,138,58,.08)", borderColor: "rgba(180,138,58,.25)", borderRight: "3px solid var(--gold)", borderRadius: "8px 22px 22px 8px" }}>
              <div className="serif" style={{ fontSize: 15, lineHeight: 1.6, fontStyle: "italic" }}>"{book.notes}"</div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function LoansScreen({ state, actions }) {
  const { loans, books } = state;
  const [tab, setTab] = useState("active");
  const loansWithBook = loans.map(l => ({ ...l, book: books.find(b => b.id === l.bookId), days: daysBetween(l.dueAt) }));

  return (
    <div className="col gap-6">
      <div className="row between" style={{ alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
        <div>
          <h1 className="screen-title">השאלות</h1>
          <div className="screen-sub">ניהול השאלות והחזרות · {loans.length} פעילות</div>
        </div>
        <button className="btn btn-primary" onClick={() => actions.openCreateLoan()}><Icon name="plus" size={16} /> השאלה חדשה</button>
      </div>

      <Segment items={[{ id:"active",label:"פעילות",count:loans.length},{ id:"history",label:"היסטוריה",count:8},{ id:"people",label:"אנשים",count:5}]} value={tab} onChange={setTab} />

      {loans.length === 0 ? (
        <Empty icon="handoff" title="אין השאלות פעילות" sub="כל הספרים נמצאים במקום שלהם 🎉"
          action={<button className="btn btn-primary" onClick={() => actions.openCreateLoan()}><Icon name="plus" size={16} /> השאלה חדשה</button>} />
      ) : (
        <div className="col gap-4">
          {loansWithBook.map(l => (
            <div key={l.id} className="card row gap-4 loan-card" style={{ alignItems: "center" }}>
              <BookCover book={l.book} width={56} height={84} />
              <div className="col grow loan-meta">
                <div className="serif" style={{ fontSize: 18, fontWeight: 700 }}>{l.book.title}</div>
                <div className="muted" style={{ fontSize: 13 }}>{l.book.author}</div>
                <div className="row gap-3 mt-2" style={{ alignItems: "center" }}>
                  <Avatar name={l.borrower} size="sm" />
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{l.borrower}</span>
                  <span className="muted" style={{ fontSize: 12 }}>· הושאל ב־{formatDate(l.loanedAt)}</span>
                </div>
                {l.note && <div className="muted mt-2" style={{ fontSize: 13, fontStyle: "italic" }}>"{l.note}"</div>}
              </div>
              <div className="col loan-actions" style={{ alignItems: "flex-end", gap: 8, minWidth: 120 }}>
                <div style={{ padding: "8px 14px", borderRadius: 12, background: l.days < 7 ? "rgba(166,74,42,.12)" : "rgba(180,138,58,.12)", color: l.days < 7 ? "var(--rust)" : "var(--gold)", fontWeight: 700, fontSize: 14 }}>
                  {l.days < 0 ? `איחור ${-l.days} ימים` : l.days === 0 ? "היום" : `בעוד ${l.days} ימים`}
                </div>
                <div className="row gap-2">
                  <button className="btn btn-sm" onClick={() => actions.remindLoan(l.id)}><Icon name="send" size={13} /> תזכרי</button>
                  <button className="btn btn-sm btn-primary" onClick={() => actions.returnLoan(l.id)}><Icon name="check" size={13} /> חזר</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function WishesScreen({ state, actions }) {
  const { wishes } = state;
  const grouped = { high: wishes.filter(w => w.priority === "high"), med: wishes.filter(w => w.priority === "med"), low: wishes.filter(w => w.priority === "low") };
  const titles = { high: "דחוף — קני בקרוב", med: "מתישהו בקרוב", low: "אולי יום אחד" };
  return (
    <div className="col gap-6">
      <div className="row between" style={{ alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
        <div>
          <h1 className="screen-title">משאלות</h1>
          <div className="screen-sub">{wishes.length} ספרים בהשתוקקות</div>
        </div>
        <button className="btn btn-primary" onClick={() => actions.openAddWish()}><Icon name="plus" size={16} /> משאלה חדשה</button>
      </div>

      {wishes.length === 0 ? (
        <Empty icon="heart" title="רשימת המשאלות ריקה" sub="הוסיפי ספרים שתרצי לקרוא יום אחד"
          action={<button className="btn btn-primary" onClick={() => actions.openAddWish()}>הוספת משאלה</button>} />
      ) : (
        <div className="col gap-6">
          {["high","med","low"].map(pri => grouped[pri].length > 0 && (
            <div key={pri}>
              <div className="row gap-3 mt-2" style={{ alignItems: "center" }}>
                <span className="serif" style={{ fontSize: 20, fontWeight: 700 }}>{titles[pri]}</span>
                <span className="muted" style={{ fontSize: 13 }}>{grouped[pri].length}</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 14 }} className="mt-3">
                {grouped[pri].map(w => (
                  <div key={w.id} className="card row gap-3" style={{ padding: 14, alignItems: "center" }}>
                    {w.coverUrl ? (
                      <img src={w.coverUrl} alt={w.title} style={{ width: 48, height: 70, objectFit: "cover", borderRadius: "3px 6px 6px 3px", flex: "0 0 auto" }} />
                    ) : (
                      <div style={{ width: 48, height: 70, borderRadius: "3px 6px 6px 3px", background: `hsl(${w.coverHue} 45% 30%)`, flex: "0 0 auto" }}></div>
                    )}
                    <div className="col grow" style={{ minWidth: 0 }}>
                      <div className="serif" style={{ fontSize: 15, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{w.title}</div>
                      <div className="muted" style={{ fontSize: 12 }}>{w.author}</div>
                      {w.reason && <div className="muted mt-2" style={{ fontSize: 11, fontStyle: "italic" }}>"{w.reason}"</div>}
                    </div>
                    <button className="btn btn-icon btn-ghost" title="קניתי" onClick={() => actions.fulfillWish(w.id)}>
                      <Icon name="check" size={16} />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function daysBetween(dateStr) {
  const target = new Date(dateStr);
  const today = new Date();
  today.setHours(0,0,0,0);
  return Math.round((target - today) / 86400000);
}
function formatDate(s) {
  if (!s) return "";
  return new Date(s).toLocaleDateString("he-IL", { day: "numeric", month: "short", year: "numeric" });
}

Object.assign(window, { HomeScreen, LibraryScreen, BookSheet, LoansScreen, WishesScreen, daysBetween, formatDate });
