/* global React, Icon, IconBtn, db */
const { useState, useEffect, useMemo, useCallback } = React;

// ============================================================
// Reading tracker — a small library: books you want, are reading,
// or have finished. With progress, rating, optional cover URL.
//
// Storage: a single kv record { books: [...] }
// Book: { id, title, author, status, progress, rating, cover, notes, addedAt, finishedAt }
// ============================================================

const READING_STATUS = [
  { id: 'want',    label: 'Want to read', icon: 'bookmark_add',  color: 'hsl(212, 85%, 60%)' },
  { id: 'reading', label: 'Reading',      icon: 'menu_book',     color: 'hsl(28, 90%, 60%)' },
  { id: 'done',    label: 'Finished',     icon: 'check_circle',  color: 'hsl(168, 60%, 50%)' },
];
const STATUS_BY_ID = Object.fromEntries(READING_STATUS.map(s => [s.id, s]));

function ReadingTool() {
  const [books, setBooks] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const [filter, setFilter] = useState('all'); // all | status id
  const [adding, setAdding] = useState(false);
  const [editId, setEditId] = useState(null);

  useEffect(() => {
    db.kv.get('readingTracker').then(rec => {
      if (Array.isArray(rec?.v?.books)) setBooks(rec.v.books);
      setLoaded(true);
    });
  }, []);

  const save = useCallback((next) => {
    setBooks(next);
    db.kv.put({ k: 'readingTracker', v: { books: next } });
  }, []);

  const addBook = (b) => {
    const id = 'b_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    save([{ ...b, id, status: 'want', addedAt: Date.now() }, ...books]);
    setAdding(false);
  };
  const updateBook = (id, patch) => {
    save(books.map(b => b.id === id ? { ...b, ...patch } : b));
  };
  const removeBook = async (id) => {
    const b = books.find(x => x.id === id);
    if (!b) return;
    const ok = await window.lhDialog.confirm({
      title: `Remove "${b.title}"?`,
      message: 'This deletes the book and any notes you\u2019ve written about it.',
      confirmLabel: 'Remove',
      danger: true,
      icon: 'delete',
    });
    if (ok) {
      save(books.filter(x => x.id !== id));
      setEditId(null);
    }
  };
  const setStatus = (id, status) => {
    const patch = { status };
    if (status === 'done') {
      patch.finishedAt = Date.now();
      patch.progress = 100;
    }
    if (status === 'reading' && !books.find(b => b.id === id)?.progress) patch.progress = 1;
    updateBook(id, patch);
  };

  // Stats
  const stats = useMemo(() => {
    const yearStart = new Date(); yearStart.setMonth(0, 1); yearStart.setHours(0,0,0,0);
    const finishedThisYear = books.filter(b => b.status === 'done' && (b.finishedAt || 0) >= yearStart.getTime()).length;
    const reading = books.filter(b => b.status === 'reading').length;
    const want = books.filter(b => b.status === 'want').length;
    return { finishedThisYear, reading, want, total: books.length };
  }, [books]);

  const visible = useMemo(() => {
    return books.filter(b => filter === 'all' || b.status === filter);
  }, [books, filter]);

  if (!loaded) return <div className="read-tool" />;

  return (
    <div className="read-tool">
      <header className="read-head">
        <div>
          <h1>Reading</h1>
          <p>Track the books in your queue, the ones you're in, and the ones you've finished.</p>
        </div>
        <button className="lh-btn primary" onClick={() => setAdding(true)}>
          <Icon name="add" />Add a book
        </button>
      </header>

      <section className="read-stats">
        <ReadStat label="Reading now" value={stats.reading} accent="hsl(28, 90%, 60%)" />
        <ReadStat label="Want to read" value={stats.want} accent="hsl(212, 85%, 60%)" />
        <ReadStat label="Finished this year" value={stats.finishedThisYear} accent="hsl(168, 60%, 50%)" />
        <ReadStat label="Total tracked" value={stats.total} />
      </section>

      {adding && (
        <BookForm onSave={addBook} onCancel={() => setAdding(false)} />
      )}

      <div className="read-filters">
        <button className={`read-filter ${filter === 'all' ? 'is-active' : ''}`} onClick={() => setFilter('all')}>
          All <em>{books.length}</em>
        </button>
        {READING_STATUS.map(s => {
          const n = books.filter(b => b.status === s.id).length;
          return (
            <button
              key={s.id}
              className={`read-filter ${filter === s.id ? 'is-active' : ''}`}
              onClick={() => setFilter(s.id)}
              style={filter === s.id ? { '--status-color': s.color } : {}}
            >
              <Icon name={s.icon} />{s.label} <em>{n}</em>
            </button>
          );
        })}
      </div>

      {visible.length === 0 ? (
        <div className="read-empty">
          <Icon name="auto_stories" />
          <div className="title">{filter === 'all' ? 'No books yet' : `Nothing in "${STATUS_BY_ID[filter].label}"`}</div>
          <div className="sub">Add a book to get started — title and author is enough.</div>
        </div>
      ) : (
        <div className="read-grid">
          {visible.map(b => (
            <BookCard
              key={b.id}
              book={b}
              expanded={editId === b.id}
              onExpand={() => setEditId(editId === b.id ? null : b.id)}
              onStatus={(s) => setStatus(b.id, s)}
              onUpdate={(patch) => updateBook(b.id, patch)}
              onRemove={() => removeBook(b.id)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function ReadStat({ label, value, accent }) {
  return (
    <div className="read-stat-card" style={accent ? { borderTop: `3px solid ${accent}` } : {}}>
      <div className="read-stat-value">{value}</div>
      <div className="read-stat-label">{label}</div>
    </div>
  );
}

// ============================================================
// BookCard — book row with cover, progress, expand-to-edit
// ============================================================
function BookCard({ book, expanded, onExpand, onStatus, onUpdate, onRemove }) {
  const s = STATUS_BY_ID[book.status] || STATUS_BY_ID.want;
  return (
    <article className={`book-card ${expanded ? 'is-expanded' : ''}`}>
      <button className="book-main" onClick={onExpand}>
        <div className="book-cover" style={book.cover ? { backgroundImage: `url(${book.cover})` } : {}}>
          {!book.cover && <span className="book-cover-letter">{(book.title || '?')[0].toUpperCase()}</span>}
        </div>
        <div className="book-meta">
          <div className="book-title">{book.title || 'Untitled'}</div>
          <div className="book-author">{book.author || 'Unknown author'}</div>
          <div className="book-status-row">
            <span className="book-status" style={{ color: s.color, background: `color-mix(in oklab, ${s.color} 16%, transparent)` }}>
              <Icon name={s.icon} />{s.label}
            </span>
            {book.rating > 0 && (
              <span className="book-rating">
                {Array.from({ length: 5 }, (_, i) => (
                  <Icon key={i} name={i < book.rating ? 'star' : 'star_outline'} />
                ))}
              </span>
            )}
          </div>
          {book.status === 'reading' && book.progress > 0 && (
            <div className="book-progress">
              <div className="book-progress-bar"><span style={{ width: `${book.progress}%`, background: s.color }} /></div>
              <span className="book-progress-num">{book.progress}%</span>
            </div>
          )}
        </div>
        <Icon name={expanded ? 'expand_less' : 'expand_more'} className="book-chev" />
      </button>

      {expanded && (
        <div className="book-drawer">
          <div className="book-row">
            <label>Status</label>
            <div className="book-status-row">
              {READING_STATUS.map(opt => (
                <button
                  key={opt.id}
                  className={`book-status-btn ${book.status === opt.id ? 'is-active' : ''}`}
                  onClick={() => onStatus(opt.id)}
                  style={book.status === opt.id ? { '--status-color': opt.color } : {}}
                >
                  <Icon name={opt.icon} />{opt.label}
                </button>
              ))}
            </div>
          </div>
          {book.status === 'reading' && (
            <div className="book-row">
              <label>Progress: {book.progress || 0}%</label>
              <input
                type="range" min="0" max="100" step="5"
                value={book.progress || 0}
                onChange={e => onUpdate({ progress: parseInt(e.target.value, 10) })}
              />
            </div>
          )}
          <div className="book-row">
            <label>Rating</label>
            <div className="book-rating-pick">
              {[1,2,3,4,5].map(r => (
                <button key={r} className="book-rating-btn" onClick={() => onUpdate({ rating: book.rating === r ? 0 : r })}>
                  <Icon name={r <= (book.rating || 0) ? 'star' : 'star_outline'} />
                </button>
              ))}
            </div>
          </div>
          <div className="book-row">
            <label>Notes</label>
            <textarea
              className="lh-input"
              rows={3}
              placeholder="What stood out? Favorite quotes?"
              value={book.notes || ''}
              onChange={e => onUpdate({ notes: e.target.value })}
            />
          </div>
          <div className="book-row">
            <label>Cover image URL (optional)</label>
            <input
              className="lh-input"
              value={book.cover || ''}
              onChange={e => onUpdate({ cover: e.target.value })}
              placeholder="https://…"
            />
          </div>
          <div className="book-drawer-foot">
            <button className="lh-btn danger" onClick={onRemove}><Icon name="delete" />Remove book</button>
          </div>
        </div>
      )}
    </article>
  );
}

// ============================================================
// BookForm — quick add
// ============================================================
function BookForm({ onSave, onCancel }) {
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');
  const submit = () => {
    if (!title.trim()) return;
    onSave({ title: title.trim(), author: author.trim(), progress: 0, rating: 0, cover: '', notes: '' });
  };
  return (
    <div className="book-form">
      <div className="book-form-fields">
        <input
          className="lh-input book-form-title"
          autoFocus
          placeholder="Title"
          value={title}
          onChange={e => setTitle(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') submit(); if (e.key === 'Escape') onCancel(); }}
        />
        <input
          className="lh-input"
          placeholder="Author"
          value={author}
          onChange={e => setAuthor(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') submit(); if (e.key === 'Escape') onCancel(); }}
        />
      </div>
      <div className="book-form-actions">
        <button className="lh-btn ghost" onClick={onCancel}>Cancel</button>
        <button className="lh-btn primary" onClick={submit} disabled={!title.trim()}>
          <Icon name="bookmark_add" />Add to "Want to read"
        </button>
      </div>
    </div>
  );
}

window.ReadingTool = ReadingTool;
