// Saved dashboard — session 26, spec §4. Aggregates every trip_item across
// every park a user has saved from (via listAllTripItems(), one joined query,
// no per-trip fetching) plus the personal reading list. This is new screen
// work over data that already existed (trips/trip_items) — nothing here is a
// new backend concept except reading_list, which was built in session 25/26a.

const CATEGORY_TO_SECTION = { do: 'do', hike: 'hikes', stay: 'stays', gear: 'gear', wildlife: 'life' };
const CATEGORY_LABELS = { do: 'To Do', hike: 'Hike', stay: 'Stay', gear: 'Gear', wildlife: 'Wildlife' };

function savedItemLabel(it) {
  const parts = [];
  const m = it.meta || {};
  if (m.miles) parts.push(m.miles + ' mi');
  if (m.elevation_ft) parts.push(m.elevation_ft + '\u2032');
  if (m.difficulty) parts.push(m.difficulty);
  if (m.price_night) parts.push('$' + m.price_night + '/night');
  if (m.vendor) parts.push(m.vendor);
  return parts.join(' \u00b7 ');
}

function SavedScreen({ go, openPark }) {
  const [loading, setLoading] = React.useState(true);
  const [items, setItems] = React.useState([]);
  const [parkIndex, setParkIndex] = React.useState([]);
  const [reading, setReading] = React.useState([]);
  const [categoryFilter, setCategoryFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('active'); // active | archive

  // reading-list add form
  const [rTitle, setRTitle] = React.useState('');
  const [rAuthor, setRAuthor] = React.useState('');
  const [rPark, setRPark] = React.useState('');
  const [rSaving, setRSaving] = React.useState(false);

  const load = React.useCallback(async () => {
    const [all, idx, rl] = await Promise.all([
      window.PH.listAllTripItems(), window.PH.getParkIndex(), window.PH.listReadingList(),
    ]);
    setItems(all); setParkIndex(idx); setReading(rl);
    if (!rPark && idx.length) setRPark(idx[0].slug);
  }, [rPark]);

  React.useEffect(() => { (async () => { setLoading(true); await load(); setLoading(false); })(); }, []);

  if (loading) return <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-3)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Loading everything you've saved…</div>;

  const byd = Object.fromEntries(parkIndex.map(p => [p.slug, p]));
  const filtered = items.filter(it => {
    const archived = it.trip && it.trip.status === 'completed';
    if (statusFilter === 'active' && archived) return false;
    if (statusFilter === 'archive' && !archived) return false;
    if (categoryFilter !== 'all' && it.category !== categoryFilter) return false;
    return true;
  });
  const totals = window.PH.tripTotals(filtered);

  const groups = {};
  for (const it of filtered) {
    const slug = it.trip ? it.trip.park_slug : 'unknown';
    (groups[slug] = groups[slug] || []).push(it);
  }
  const groupSlugs = Object.keys(groups).sort((a, b) => {
    const pa = byd[a], pb = byd[b];
    return (pa ? pa.stamp_no : 999) - (pb ? pb.stamp_no : 999);
  });

  const toggleDone = async (it) => {
    const row = await window.PH.toggleTripItemDone(it.id, !it.done);
    setItems(prev => prev.map(x => x.id === it.id ? { ...x, done: row.done } : x));
  };
  const removeItem = async (it) => {
    await window.PH.removeTripItem(it.id);
    setItems(prev => prev.filter(x => x.id !== it.id));
  };

  const addBook = async () => {
    if (!rTitle.trim()) return;
    setRSaving(true);
    try {
      await window.PH.addReadingItem({ title: rTitle.trim(), author: rAuthor.trim() || null, park_slug: rPark || null });
      setRTitle(''); setRAuthor('');
      setReading(await window.PH.listReadingList());
    } finally { setRSaving(false); }
  };
  const setBookStatus = async (id, status) => {
    await window.PH.updateReadingItem(id, { status });
    setReading(prev => prev.map(b => b.id === id ? { ...b, status } : b));
  };
  const removeBook = async (id) => {
    await window.PH.removeReadingItem(id);
    setReading(prev => prev.filter(b => b.id !== id));
  };

  const CAT_CHIPS = [
    { k: 'all', l: 'All' }, { k: 'do', l: 'To Do' }, { k: 'hike', l: 'Hikes' },
    { k: 'stay', l: 'Stays' }, { k: 'gear', l: 'Gear' }, { k: 'wildlife', l: 'Wildlife' },
  ];

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%', paddingBottom: 110 }}>
      <div style={{ padding: '58px 22px 0' }}>
        <Caps s={10} c="var(--accent)">Your Kit</Caps>
        <h1 style={{ margin: '6px 0 0', fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 40, lineHeight: 0.95, letterSpacing: '-0.02em', color: 'var(--ink)' }}>Everything you've saved.</h1>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, margin: '22px 22px 0', padding: '18px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <Metric n={filtered.length} l="Items"/>
        <Metric n={totals.miles || 0} l="Trail miles"/>
        <Metric n={totals.stay_per_night ? '$' + totals.stay_per_night : '\u2014'} l="Lodging/nt"/>
      </div>

      <div style={{ display: 'flex', gap: 8, padding: '18px 22px 0', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {CAT_CHIPS.map(c => <Chip key={c.k} active={categoryFilter === c.k} onClick={() => setCategoryFilter(c.k)}>{c.l}</Chip>)}
      </div>

      <div style={{ padding: '14px 22px 0' }}>
        <div style={{ position: 'relative', display: 'flex', background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 100, padding: 4, maxWidth: 220 }}>
          <div style={{ position: 'absolute', top: 4, left: statusFilter === 'active' ? 4 : '50%', width: 'calc(50% - 4px)', height: 'calc(100% - 8px)', background: 'var(--ink)', borderRadius: 100, transition: 'left 220ms ease' }}/>
          {['active', 'archive'].map(s => (
            <button key={s} onClick={() => setStatusFilter(s)} style={{
              flex: 1, position: 'relative', zIndex: 1, border: 'none', background: 'none', padding: '8px 4px',
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase',
              color: statusFilter === s ? 'var(--bg)' : 'var(--ink-3)', cursor: 'pointer',
            }}>{s === 'active' ? 'Active' : 'Archive'}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '22px 22px 0' }}>
        {groupSlugs.length === 0 && (
          <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontStyle: 'italic', color: 'var(--ink-3)', padding: '10px 0 30px' }}>Nothing saved yet. Open any park and tap + on a hike, stay, or gear item.</div>
        )}
        {groupSlugs.map(slug => {
          const p = byd[slug];
          return (
            <div key={slug} style={{ marginBottom: 22 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', borderBottom: '1px solid var(--line)', paddingBottom: 8, marginBottom: 4 }}>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink)' }}>
                  {p ? p.name : slug}{p && <span style={{ color: 'var(--ink-3)' }}> &middot; Stamp {String(p.stamp_no).padStart(2, '0')}</span>}
                </span>
                <Caps s={9}>{groups[slug].length}</Caps>
              </div>
              {groups[slug].map(it => (
                <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--line)' }}>
                  <button onClick={() => toggleDone(it)} style={{
                    width: 22, height: 22, borderRadius: 6, flexShrink: 0, border: '1px solid ' + (it.done ? 'var(--accent)' : 'var(--line)'),
                    background: it.done ? 'var(--accent)' : 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{it.done && I.check('var(--bg)')}</button>
                  <button onClick={() => openPark(slug, CATEGORY_TO_SECTION[it.category] || 'do')} style={{ flex: 1, textAlign: 'left', border: 'none', background: 'none', padding: 0, cursor: 'pointer' }}>
                    <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, color: 'var(--ink)', textDecoration: it.done ? 'line-through' : 'none', opacity: it.done ? 0.55 : 1 }}>{it.title}</div>
                    <Caps s={9} style={{ display: 'block', marginTop: 2, textTransform: 'none', letterSpacing: 0 }}>{CATEGORY_LABELS[it.category]}{savedItemLabel(it) ? ' \u00b7 ' + savedItemLabel(it) : ''}</Caps>
                  </button>
                  <button onClick={() => removeItem(it)} title="Remove" style={{ width: 26, height: 26, borderRadius: '50%', border: '1px solid var(--line)', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-3)', flexShrink: 0 }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                  </button>
                </div>
              ))}
            </div>
          );
        })}
      </div>

      <SectionHead eyebrow="Before, During, or After" title="Reading List" meta={reading.length}/>
      <div style={{ padding: '0 22px' }}>
        <div style={{ border: '1px solid var(--line)', borderRadius: 12, padding: 16, background: 'var(--paper)', marginBottom: 14 }}>
          <input value={rTitle} onChange={e => setRTitle(e.target.value)} placeholder="Book title" style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'DM Sans, sans-serif', fontSize: 14, marginBottom: 8 }}/>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            <input value={rAuthor} onChange={e => setRAuthor(e.target.value)} placeholder="Author (optional)" style={{ flex: 1, padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'DM Sans, sans-serif', fontSize: 13 }}/>
            <select value={rPark} onChange={e => setRPark(e.target.value)} style={{ flex: 1, padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'DM Sans, sans-serif', fontSize: 13 }}>
              <option value="">No park (general)</option>
              {parkIndex.map(p => <option key={p.slug} value={p.slug}>{p.name}</option>)}
            </select>
          </div>
          <button disabled={rSaving || !rTitle.trim()} onClick={addBook} style={{ padding: '9px 16px', background: 'var(--ink)', color: 'var(--bg)', border: 'none', borderRadius: 100, cursor: rSaving ? 'default' : 'pointer', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: (rSaving || !rTitle.trim()) ? 0.5 : 1 }}>Add to list</button>
        </div>

        {reading.length === 0 && (
          <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontStyle: 'italic', color: 'var(--ink-3)', padding: '4px 0 20px' }}>No books yet. Add the ones you want to read before, during, or after the trip.</div>
        )}
        {reading.map(b => {
          const p = b.park_slug ? byd[b.park_slug] : null;
          return (
            <div key={b.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 0', borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
              <div style={{ flex: 1, minWidth: 160 }}>
                <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 15, color: 'var(--ink)' }}>{b.title}</div>
                <Caps s={9} style={{ display: 'block', marginTop: 2, textTransform: 'none', letterSpacing: 0 }}>{[b.author, p ? p.name : null].filter(Boolean).join(' \u00b7 ')}</Caps>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                {['to_read', 'reading', 'finished'].map(s => (
                  <button key={s} onClick={() => setBookStatus(b.id, s)} style={{
                    padding: '5px 10px', borderRadius: 100, border: '1px solid ' + (b.status === s ? 'var(--ink)' : 'var(--line)'),
                    background: b.status === s ? 'var(--ink)' : 'transparent', color: b.status === s ? 'var(--bg)' : 'var(--ink-3)',
                    fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer',
                  }}>{s === 'to_read' ? 'To Read' : s === 'reading' ? 'Reading' : 'Finished'}</button>
                ))}
              </div>
              <button onClick={() => removeBook(b.id)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--ink-3)' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { SavedScreen });
