// itrymo — Favorites: persistent saved-places store + saved view.
// Loaded after proto-shared.jsx. Uses T, Icon, PlaceCard, PLACES.

const FAV_KEY = 'itrymo_favorites';

function readFavs() {
  try { return JSON.parse(localStorage.getItem(FAV_KEY) || '[]'); } catch { return []; }
}
function writeFavs(ids) {
  try { localStorage.setItem(FAV_KEY, JSON.stringify(ids)); } catch (e) {}
  window.dispatchEvent(new Event('itrymo:favs:update'));
}
function toggleFav(id) {
  const ids = readFavs();
  const i = ids.indexOf(id);
  if (i >= 0) ids.splice(i, 1); else ids.unshift(id); // newest first
  writeFavs(ids);
}
function clearFavs() { writeFavs([]); }

// Subscribe to the whole list — re-renders on any change anywhere.
function useFavorites() {
  const [ids, setIds] = React.useState(readFavs);
  React.useEffect(() => {
    const h = () => setIds(readFavs());
    window.addEventListener('itrymo:favs:update', h);
    return () => window.removeEventListener('itrymo:favs:update', h);
  }, []);
  return ids;
}
function useIsFav(id) {
  const ids = useFavorites();
  return ids.includes(id);
}

// ─────────────────────────────────────────────────────────────
// FavoritesView — Saved ♡ + Tried ✓ with bucket tabs
// ─────────────────────────────────────────────────────────────
const BUCKET_TABS = [
  { id: 'all',  label: 'All' },
  { id: 'eat',  label: 'Eat' },
  { id: 'do',   label: 'Do'  },
  { id: 'stay', label: 'Stay'},
];

function MyPlacesEmpty({ mode, bucket, surface }) {
  const icon = mode === 'tried' ? 'tried' : 'heart';
  const msg  = mode === 'tried'
    ? { title: 'Nothing tried yet', sub: 'Tap "I\'ve Tried" on a place after visiting it.' }
    : { title: 'No saved places yet', sub: 'Tap ♡ on any place to save it for later.' };
  return (
    <div style={{
      padding: surface === 'mobile' ? '56px 24px' : '72px 24px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 28, background: T.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={22} color={T.muted} />
      </div>
      <div style={{ fontSize: 17, fontWeight: 700, color: T.ink }}>{msg.title}</div>
      <div style={{ fontSize: 13, color: T.muted, maxWidth: 300, lineHeight: 1.5 }}>{msg.sub}</div>
    </div>
  );
}

function FavoritesView({ surface = 'web', onClose, onOpenPlace }) {
  useEscClose(onClose);
  const favIds   = useFavorites();
  const triedIds = useTried();
  const [mode,   setMode]   = React.useState('saved');   // 'saved' | 'tried'
  const [bucket, setBucket] = React.useState('all');

  // All places for current mode
  const allPlaces = (mode === 'saved' ? favIds : triedIds)
    .map((id) => PLACES.find((p) => p.id === id)).filter(Boolean);

  // Filtered by bucket tab
  const shown = bucket === 'all' ? allPlaces : allPlaces.filter((p) => p.bucket === bucket);

  // Counts per bucket for badges
  const counts = React.useMemo(() => {
    const c = { all: allPlaces.length, eat: 0, do: 0, stay: 0 };
    allPlaces.forEach((p) => { if (c[p.bucket] !== undefined) c[p.bucket]++; });
    return c;
  }, [allPlaces]);

  const pad = surface === 'mobile' ? '14px 18px' : '18px 24px';

  const header = (
    <div style={{ flexShrink: 0 }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: pad, borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        {surface === 'mobile' && (
          <button onClick={onClose} style={{
            all: 'unset', cursor: 'pointer', width: 34, height: 34, borderRadius: 17,
            background: T.bg, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="chevR" size={16} style={{ transform: 'rotate(180deg)' }} />
          </button>
        )}
        <h2 style={{ fontSize: surface === 'mobile' ? 18 : 20, fontWeight: 700, letterSpacing: -0.4, margin: 0, flex: 1 }}>
          My Places
        </h2>
        {surface === 'web' && (
          <button onClick={onClose} style={{
            all: 'unset', cursor: 'pointer', width: 30, height: 30, borderRadius: 15,
            background: '#F4EFE6', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="close" size={13} />
          </button>
        )}
      </div>

      {/* Mode toggle: Saved / Tried */}
      <div style={{
        display: 'flex', gap: 8, padding: `12px ${surface === 'mobile' ? '18px' : '24px'} 0`,
      }}>
        {[
          { id: 'saved', icon: 'heart', label: 'Saved', count: favIds.length },
          { id: 'tried', icon: 'tried', label: "I've Tried", count: triedIds.length },
        ].map(({ id, icon, label, count }) => {
          const on = mode === id;
          return (
            <button key={id} onClick={() => { setMode(id); setBucket('all'); }} style={{
              all: 'unset', cursor: 'pointer', flex: 1, height: 44, borderRadius: 12,
              background: on ? T.selBg : T.bg,
              color: on ? T.selFg : T.faintInk,
              border: `1px solid ${on ? T.selBg : T.borderSoft}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              fontWeight: 600, fontSize: 14, transition: 'background .12s',
            }}>
              <Icon name={icon} size={16} color={on ? T.selFg : T.faintInk} />
              {label}
              {count > 0 && (
                <span style={{
                  fontSize: 11, fontWeight: 700, minWidth: 18, height: 18,
                  borderRadius: 9, background: on ? 'rgba(255,255,255,0.25)' : T.border,
                  color: on ? T.selFg : T.muted,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: '0 5px',
                }}>{count}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Bucket tabs: All / Eat / Do / Stay */}
      <div style={{
        display: 'flex', gap: 6, padding: `10px ${surface === 'mobile' ? '18px' : '24px'} 12px`,
        borderBottom: `1px solid ${T.borderSoft}`,
      }}>
        {BUCKET_TABS.map(({ id, label }) => {
          const on = bucket === id;
          const c  = counts[id] ?? 0;
          if (id !== 'all' && c === 0) return null;
          return (
            <button key={id} onClick={() => setBucket(id)} style={{
              all: 'unset', cursor: 'pointer', height: 30, padding: '0 12px', borderRadius: 999,
              background: on ? T.ink : T.bg,
              color: on ? '#fff' : T.faintInk,
              border: `1px solid ${on ? T.ink : T.borderSoft}`,
              fontSize: 12, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              {label}
              {c > 0 && (
                <span style={{
                  fontSize: 10, fontWeight: 700,
                  color: on ? 'rgba(255,255,255,0.7)' : T.muted,
                }}>{c}</span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );

  const body = shown.length === 0 ? (
    <MyPlacesEmpty mode={mode} bucket={bucket} surface={surface} />
  ) : surface === 'mobile' ? (
    <div style={{ padding: '14px 18px 28px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      {shown.map((p) => <PlaceCard key={p.id} place={p} variant="wide" onOpen={onOpenPlace} />)}
    </div>
  ) : (
    <div style={{ padding: 24, display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))' }}>
      {shown.map((p) => <PlaceCard key={p.id} place={p} variant="grid" onOpen={onOpenPlace} />)}
    </div>
  );

  if (surface === 'mobile') {
    return (
      <div style={{
        position: 'absolute', inset: 0, background: '#fff', zIndex: 70,
        display: 'flex', flexDirection: 'column', animation: 'itrymo-slideup .22s ease',
      }} role="dialog" aria-modal="true" aria-label="My Places">
        {header}
        <div style={{ flex: 1, overflowY: 'auto', background: T.bg }}>{body}</div>
      </div>
    );
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 70, background: 'rgba(20,18,14,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      animation: 'itrymo-fade .18s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="My Places" style={{
        width: '100%', maxWidth: 920, maxHeight: '88vh', background: '#fff',
        borderRadius: 18, overflow: 'hidden', display: 'flex', flexDirection: 'column',
        boxShadow: '0 30px 80px rgba(0,0,0,0.30)', animation: 'itrymo-pop .2s ease',
      }}>
        {header}
        <div style={{ flex: 1, overflowY: 'auto', background: T.bg }}>{body}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// "I've Tried" — same pattern as favorites, separate localStorage key
// ─────────────────────────────────────────────────────────────
const TRIED_KEY = 'itrymo_tried';

function readTried()      { try { return JSON.parse(localStorage.getItem(TRIED_KEY) || '[]'); } catch { return []; } }
function writeTried(ids)  { try { localStorage.setItem(TRIED_KEY, JSON.stringify(ids)); } catch {} window.dispatchEvent(new Event('itrymo:tried:update')); }
function toggleTried(id)  { const ids = readTried(); const i = ids.indexOf(id); if (i >= 0) ids.splice(i, 1); else ids.unshift(id); writeTried(ids); }

function useTried() {
  const [ids, setIds] = React.useState(readTried);
  React.useEffect(() => {
    const h = () => setIds(readTried());
    window.addEventListener('itrymo:tried:update', h);
    return () => window.removeEventListener('itrymo:tried:update', h);
  }, []);
  return ids;
}
function useIsTried(id) { return useTried().includes(id); }

Object.assign(window, {
  readFavs, writeFavs, toggleFav, clearFavs, useFavorites, useIsFav, FavoritesView,
  readTried, writeTried, toggleTried, useTried, useIsTried,
});
