/* global React, ReactDOM, HomeScreen, LibraryScreen, BookSheet, LoansScreen, WishesScreen, ChatHubScreen, ChatScreen, AddBookModal, CreateLoanModal, AddWishModal, Icon, useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle, TweakSelect, AuthGate, AUTH_PIN_KEY */
const { useState, useMemo, useEffect, useRef } = React;

const TWEAK_DEFAULTS = {
  "theme": "glass",
  "accent": "#b48a3a",
  "showActivity": true,
  "fontHeadline": "serif"
};

const LS_KEYS = { books: "mai_books", loans: "mai_loans", wishes: "mai_wishes", activity: "mai_activity" };
const WORKER_URL = "https://mai-library-api.workers.dev";
const WORKER_KEY_LS = "mai_worker_key";

function loadLS(key, fallback) {
  try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fallback; } catch { return fallback; }
}
function saveLS(key, val) {
  try { localStorage.setItem(key, JSON.stringify(val)); } catch {}
}

async function syncToWorker(data) {
  const key = localStorage.getItem(WORKER_KEY_LS);
  if (!key) return;
  try {
    await fetch(`${WORKER_URL}/sync`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Api-Key": key },
      body: JSON.stringify(data),
    });
  } catch {}
}

/* ── Account Menu ── */
function AccountMenu({ onLock, onReset }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    document.addEventListener("touchstart", h);
    return () => { document.removeEventListener("mousedown", h); document.removeEventListener("touchstart", h); };
  }, []);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className="btn btn-icon btn-ghost"
        onClick={() => setOpen(o => !o)}
        title="חשבון"
        style={{ position: "relative" }}
      >
        <Icon name="user" size={18} />
      </button>
      {open && (
        <div style={{
          position: "absolute",
          top: "calc(100% + 8px)",
          insetInlineEnd: 0,
          minWidth: 180,
          background: "var(--paper-card)",
          border: "1px solid var(--line-strong)",
          borderRadius: 14,
          boxShadow: "0 12px 32px -8px rgba(20,10,4,.25)",
          zIndex: 300,
          overflow: "hidden",
          backdropFilter: "blur(12px)",
        }}>
          <div style={{ padding: "12px 16px 8px", borderBottom: "1px solid var(--line)" }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>הספרייה של מאי</div>
            <div style={{ fontSize: 11, color: "var(--ink-mute)" }}>גישה אישית</div>
          </div>
          <button
            className="btn btn-ghost"
            style={{ width: "100%", justifyContent: "flex-start", borderRadius: 0, padding: "10px 16px", gap: 10, fontSize: 14 }}
            onClick={() => { setOpen(false); onLock(); }}
          >
            <Icon name="bookmark" size={15} /> נעלי את הספרייה
          </button>
          <button
            className="btn btn-ghost"
            style={{ width: "100%", justifyContent: "flex-start", borderRadius: 0, padding: "10px 16px", gap: 10, fontSize: 14, color: "var(--rust)" }}
            onClick={() => {
              if (confirm("למחוק את קוד הגישה?")) {
                localStorage.removeItem(AUTH_PIN_KEY);
                setOpen(false);
                onReset();
              }
            }}
          >
            <Icon name="trash" size={15} /> מחקי קוד PIN
          </button>
        </div>
      )}
    </div>
  );
}

function App() {
  const [authed, setAuthed] = useState(() => {
    // If no PIN set yet, skip auth gate
    return !localStorage.getItem(AUTH_PIN_KEY);
  });
  const [tab, setTab] = useState("home");
  const [openBookId, setOpenBookId] = useState(null);
  const [openChatId, setOpenChatId] = useState(null);

  const [books, setBooks] = useState(() => loadLS(LS_KEYS.books, window.LIBRARY_DATA.BOOKS));
  const [loans, setLoans] = useState(() => loadLS(LS_KEYS.loans, window.LIBRARY_DATA.LOANS));
  const [wishes, setWishes] = useState(() => loadLS(LS_KEYS.wishes, window.LIBRARY_DATA.WISHES));
  const [activity, setActivity] = useState(() => loadLS(LS_KEYS.activity, window.LIBRARY_DATA.ACTIVITY));

  useEffect(() => saveLS(LS_KEYS.books, books), [books]);
  useEffect(() => saveLS(LS_KEYS.loans, loans), [loans]);
  useEffect(() => saveLS(LS_KEYS.wishes, wishes), [wishes]);
  useEffect(() => saveLS(LS_KEYS.activity, activity), [activity]);

  // Debounced sync to Cloudflare Worker (for nightly backup)
  const syncTimer = useRef(null);
  useEffect(() => {
    clearTimeout(syncTimer.current);
    syncTimer.current = setTimeout(() => {
      syncToWorker({ books, loans, wishes, activity });
    }, 10000);
    return () => clearTimeout(syncTimer.current);
  }, [books, loans, wishes, activity]);

  const [addBookOpen, setAddBookOpen] = useState(false);
  const [createLoanOpen, setCreateLoanOpen] = useState(false);
  const [createLoanForBook, setCreateLoanForBook] = useState(null);
  const [addWishOpen, setAddWishOpen] = useState(false);

  const [toast, setToast] = useState(null);
  const showToast = (text) => { setToast(text); setTimeout(() => setToast(null), 2400); };

  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    document.documentElement.classList.remove("theme-parchment", "theme-walnut", "theme-sage", "theme-glass");
    document.documentElement.classList.add(`theme-${tw.theme}`);
  }, [tw.theme]);

  useEffect(() => {
    document.documentElement.style.setProperty("--gold", tw.accent);
    const num = parseInt(tw.accent.slice(1), 16);
    const r = (num >> 16) & 0xff, g = (num >> 8) & 0xff, b = num & 0xff;
    document.documentElement.style.setProperty("--gold-2", `rgb(${Math.min(255,r+25)},${Math.min(255,g+25)},${Math.min(255,b+25)})`);
  }, [tw.accent]);

  useEffect(() => {
    document.documentElement.style.setProperty("--font-serif",
      tw.fontHeadline === "serif" ? '"Frank Ruhl Libre", serif' :
      tw.fontHeadline === "display" ? '"Suez One", serif' :
      '"Heebo", sans-serif');
  }, [tw.fontHeadline]);

  const actions = useMemo(() => ({
    go: setTab,
    setQuery: () => {},
    openBook: (id) => setOpenBookId(id),
    openAddBook: () => setAddBookOpen(true),
    openCreateLoan: (bookId) => { setCreateLoanForBook(bookId || null); setCreateLoanOpen(true); },
    openAddWish: () => setAddWishOpen(true),
    openChat: (id) => setOpenChatId(id),
    addBook: (data) => {
      const id = "b" + (Date.now() % 100000);
      const today = new Date().toISOString().slice(0, 10);
      const hue = Math.floor(Math.random() * 360);
      const book = {
        id, title: data.title, author: data.author || "—", genre: data.genre, year: +data.year || new Date().getFullYear(),
        pages: +data.pages || 240, status: "available", rating: 0,
        spineColor: `hsl(${hue} 35% 30%)`, coverHue: hue,
        addedAt: today, notes: data.notes || "", tags: [], progress: 0,
        coverUrl: data.coverUrl || "",
      };
      setBooks(bs => [book, ...bs]);
      setActivity(a => [{ id: "a" + Date.now(), type: "add", text: `הוספת "${data.title}" לספרייה`, date: today }, ...a]);
      showToast(`"${data.title}" נוסף לספרייה`);
    },
    setCover: (bookId, coverUrl) => {
      setBooks(bs => bs.map(b => b.id === bookId ? { ...b, coverUrl } : b));
      showToast("הכריכה עודכנה");
    },
    addLoan: (data) => {
      const id = "l" + (Date.now() % 100000);
      const today = new Date().toISOString().slice(0, 10);
      const book = books.find(b => b.id === data.bookId);
      setLoans(ls => [...ls, { id, bookId: data.bookId, borrower: data.borrower, borrowerAvatar: data.borrower[0], loanedAt: today, dueAt: data.dueAt || addWeeks(today, 4), note: data.note }]);
      setBooks(bs => bs.map(b => b.id === data.bookId ? { ...b, status: "loaned" } : b));
      setActivity(a => [{ id: "a" + Date.now(), type: "loan", text: `השאלת "${book?.title}" ל${data.borrower}`, date: today }, ...a]);
      showToast(`"${book?.title}" הושאל ל${data.borrower}`);
    },
    addWish: (data) => {
      const id = "w" + (Date.now() % 100000);
      const today = new Date().toISOString().slice(0, 10);
      setWishes(ws => [{ id, title: data.title, author: data.author, reason: data.reason, priority: data.priority, addedAt: today, coverHue: Math.floor(Math.random() * 360) }, ...ws]);
      showToast(`"${data.title}" נוסף למשאלות`);
    },
    fulfillWish: (id) => {
      setWishes(ws => ws.filter(w => w.id !== id));
      showToast("המשאלה התגשמה ✨");
    },
    remindLoan: (id) => {
      const l = loans.find(x => x.id === id);
      showToast(`תזכורת נשלחה ל${l?.borrower}`);
    },
    returnLoan: (id) => {
      const l = loans.find(x => x.id === id);
      const b = books.find(x => x.id === l?.bookId);
      setLoans(ls => ls.filter(x => x.id !== id));
      setBooks(bs => bs.map(x => x.id === l?.bookId ? { ...x, status: "available" } : x));
      setActivity(a => [{ id: "a" + Date.now(), type: "return", text: `החזרת "${b?.title}" מ${l?.borrower}`, date: new Date().toISOString().slice(0, 10) }, ...a]);
      showToast(`"${b?.title}" חזר 🎉`);
      setOpenBookId(null);
    },
    startReading: (id) => {
      setBooks(bs => bs.map(b => b.id === id ? { ...b, status: "reading", progress: 0.05 } : b));
      showToast("התחלת קריאה");
    },
    markFinished: (id) => {
      setBooks(bs => bs.map(b => b.id === id ? { ...b, status: "available", progress: 1 } : b));
      showToast("סיימת! 📖");
    },
    rateBook: (id, rating) => {
      setBooks(bs => bs.map(b => b.id === id ? { ...b, rating } : b));
    },
  }), [books, loans]);

  const state = { books, loans, wishes, activity, tweaks: tw };
  const openBook = openBookId ? books.find(b => b.id === openBookId) : null;

  if (!authed) {
    return <AuthGate onAuth={() => setAuthed(true)} />;
  }

  const tabs = [
    { id: "home", label: "בית", icon: "home" },
    { id: "library", label: "ספרייה", icon: "shelf" },
    { id: "loans", label: "השאלות", icon: "handoff" },
    { id: "wishes", label: "משאלות", icon: "heart" },
    { id: "chat", label: "שיחה", icon: "chat" },
  ];

  return (
    <div className="app-root">
      <div className="shell">
        <div className="topbar">
          <div className="brand">
            <div className="brand-mark">מ</div>
            <div>
              <div className="brand-name">הספרייה של מאי</div>
              <div className="brand-sub">הקטלוג המוחשי</div>
            </div>
          </div>
          <div className="row gap-2">
            <button className="btn btn-icon btn-ghost" title="חיפוש"><Icon name="search" size={18} /></button>
            <AccountMenu
              onLock={() => setAuthed(false)}
              onReset={() => setAuthed(true)}
            />
          </div>
        </div>

        {openChatId ? (
          <ChatScreen agentId={openChatId} state={state} actions={actions} onBack={() => setOpenChatId(null)} />
        ) : (
          <>
            {tab === "home"    && <HomeScreen    state={state} actions={actions} />}
            {tab === "library" && <LibraryScreen state={state} actions={actions} />}
            {tab === "loans"   && <LoansScreen   state={state} actions={actions} />}
            {tab === "wishes"  && <WishesScreen  state={state} actions={actions} />}
            {tab === "chat"    && <ChatHubScreen state={state} actions={actions} />}
          </>
        )}
      </div>

      <nav className="nav">
        {tabs.map(t => (
          <button
            key={t.id}
            className={`nav-tab ${tab === t.id && !openChatId ? "active" : ""}`}
            onClick={() => { setTab(t.id); setOpenChatId(null); }}
          >
            <Icon name={t.icon} size={18} />
            <span className="nav-label">{t.label}</span>
          </button>
        ))}
      </nav>

      {openBook && (
        <BookSheet book={openBook} state={state} actions={actions} onClose={() => setOpenBookId(null)} />
      )}

      <AddBookModal open={addBookOpen} onClose={() => setAddBookOpen(false)} onAdd={actions.addBook} />
      <CreateLoanModal open={createLoanOpen} onClose={() => { setCreateLoanOpen(false); setCreateLoanForBook(null); }} books={books} preselectedBookId={createLoanForBook} onAdd={actions.addLoan} />
      <AddWishModal open={addWishOpen} onClose={() => setAddWishOpen(false)} onAdd={actions.addWish} />

      {toast && (
        <div style={{
          position: "fixed",
          bottom: 96,
          left: "50%",
          transform: "translateX(-50%)",
          padding: "12px 22px",
          borderRadius: 999,
          background: "var(--walnut)",
          color: "var(--paper)",
          fontSize: 14,
          fontWeight: 600,
          boxShadow: "0 12px 32px -8px rgba(20,10,4,.4)",
          zIndex: 200,
          animation: "toast-in .3s ease",
          whiteSpace: "nowrap",
        }}>
          {toast}
          <style>{`@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 10px); } to { opacity: 1; transform: translate(-50%, 0); } }`}</style>
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="ערכת נושא">
          <TweakRadio
            label="רקע"
            value={tw.theme}
            onChange={v => setTweak("theme", v)}
            options={[
              { value: "glass", label: "מוחשית" },
              { value: "parchment", label: "קלף" },
              { value: "walnut", label: "אגוז" },
              { value: "sage", label: "מרווה" },
            ]}
          />
          <TweakColor
            label="צבע הדגשה"
            value={tw.accent}
            onChange={v => setTweak("accent", v)}
            options={["#b48a3a", "#a64a2a", "#4a6a3a", "#6a3a5a", "#2e5d7a"]}
          />
        </TweakSection>
        <TweakSection label="טיפוגרפיה">
          <TweakSelect
            label="כותרות"
            value={tw.fontHeadline}
            onChange={v => setTweak("fontHeadline", v)}
            options={[
              { value: "serif", label: "סריף קלאסי (Frank Ruhl)" },
              { value: "display", label: "סריף דרמטי (Suez One)" },
              { value: "sans", label: "סן-סריף (Heebo)" },
            ]}
          />
        </TweakSection>
        <TweakSection label="תוכן">
          <TweakToggle
            label="הצג פעילות אחרונה בבית"
            value={tw.showActivity}
            onChange={v => setTweak("showActivity", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function addWeeks(date, n) {
  const d = new Date(date);
  d.setDate(d.getDate() + n * 7);
  return d.toISOString().slice(0, 10);
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
