// Unified library page with four tabs (Loved / Wishlist / Stuff you own /
// My lists) sharing a stable header so switching feels instant.

const TAB_DEFS = [
  { id: 'loved',    label: 'Loved',         icon: 'heart' },
  { id: 'wishlist', label: 'Wishlist',      icon: 'star'  },
  { id: 'owned',    label: 'Stuff you own', icon: 'check' },
  { id: 'lists',    label: 'My lists',      icon: 'list'  },
];

function CollectionsPage({
  kind,
  savedIds,
  essentialsByStage,
  productMap,
  userLists,
  customOwnedItems,
  onChangeKind,
  onOpenProduct,
  onSave,
  onShare,
  onAddCustomOwned,
  onRemoveCustomOwned,
  onOpenList,
  onCreateList,
}) {
  const lovedItems = useMemo(
    () => savedIds.map(id => productMap[id]).filter(Boolean),
    [savedIds, productMap]
  );

  const { wishlistItems, ownedItems } = useMemo(() => {
    const want = []; const own = []; const seen = { want: new Set(), own: new Set() };
    Object.entries(essentialsByStage || {}).forEach(([stage, picks]) => {
      Object.entries(picks || {}).forEach(([itemId, pick]) => {
        if (!pick || !pick.pickedProductId) return;
        const p = productMap[pick.pickedProductId];
        if (!p) return;
        if (pick.owned) {
          if (!seen.own.has(p.id)) { seen.own.add(p.id); own.push(p); }
        } else {
          if (!seen.want.has(p.id)) { seen.want.add(p.id); want.push(p); }
        }
      });
    });
    return { wishlistItems: want, ownedItems: own };
  }, [essentialsByStage, productMap]);

  const counts = {
    loved:    lovedItems.length,
    wishlist: wishlistItems.length,
    owned:    ownedItems.length + (customOwnedItems || []).length,
    lists:    (userLists || []).length,
  };

  const tabIcon = (id, current) => {
    const sw = current ? 1.9 : 1.6;
    if (id === 'heart') return <svg width="14" height="14" viewBox="0 0 24 24" fill={current ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth={sw}><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>;
    if (id === 'star')  return <svg width="14" height="14" viewBox="0 0 24 24" fill={current ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth={sw}><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>;
    if (id === 'check') return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={current ? 2.4 : 1.9}><circle cx="12" cy="12" r="9.5"/><path d="M7.5 12.5l3 3L17 9"/></svg>;
    return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={sw}><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>;
  };

  return (
    <div className="page collections-page">
      <div className="collections-pagehead">
        <div className="collections-pagehead-l">
          <div className="page-eyebrow">Your library</div>
          <h1 className="page-title">Everything <em>you've kept.</em></h1>
          <p className="page-sub">A single place for what you've loved, what you want, what you've got — and the lists you've built. Switch tabs to roam through them.</p>
        </div>
        <aside className="collections-pagehead-stats">
          <div className="collections-stat-grid">
            <div className="collections-stat collections-stat--loved"><span className="num">{counts.loved}</span><span className="lbl">Loved</span></div>
            <div className="collections-stat collections-stat--wishlist"><span className="num">{counts.wishlist}</span><span className="lbl">Wishlist</span></div>
            <div className="collections-stat collections-stat--owned"><span className="num">{counts.owned}</span><span className="lbl">Owned</span></div>
            <div className="collections-stat collections-stat--lists"><span className="num">{counts.lists}</span><span className="lbl">Lists</span></div>
          </div>
        </aside>
      </div>

      <div className="collections-tabs collections-tabs--big" role="tablist">
        {TAB_DEFS.map(t => (
          <button
            key={t.id}
            role="tab"
            aria-selected={kind === t.id}
            className={`collections-tab collections-tab--${t.id}${kind === t.id ? ' is-current' : ''}`}
            onClick={() => onChangeKind(t.id)}
          >
            <span className="collections-tab-icon">{tabIcon(t.icon, kind === t.id)}</span>
            <span className="collections-tab-label">{t.label}</span>
            <span className="count">{counts[t.id]}</span>
          </button>
        ))}
      </div>

      <div className="collections-body">
        {kind === 'loved' && (
          <CollectionGrid
            items={lovedItems}
            savedIds={savedIds}
            onOpenProduct={onOpenProduct}
            onSave={onSave}
            emptyTitle="Nothing loved yet"
            emptyBody={<>Tap the heart on any product to keep it in here.</>}
          />
        )}
        {kind === 'wishlist' && (
          <CollectionGrid
            items={wishlistItems}
            savedIds={savedIds}
            onOpenProduct={onOpenProduct}
            onSave={onSave}
            emptyTitle="Nothing on your wishlist"
            emptyBody={<>Open an essential and tap "Pick this one" — it'll land here.</>}
          />
        )}
        {kind === 'owned' && (
          <OwnedTabContent
            ownedItems={ownedItems}
            customOwnedItems={customOwnedItems || []}
            savedIds={savedIds}
            onOpenProduct={onOpenProduct}
            onSave={onSave}
            onAddCustom={onAddCustomOwned}
            onRemoveCustom={onRemoveCustomOwned}
          />
        )}
        {kind === 'lists' && (
          <ListsTabContent
            userLists={userLists || []}
            productMap={productMap}
            onOpenList={onOpenList}
            onCreateList={onCreateList}
          />
        )}
      </div>
    </div>
  );
}

function CollectionGrid({ items, savedIds, onOpenProduct, onSave, emptyTitle, emptyBody }) {
  if (!items.length) {
    return (
      <div className="empty collections-empty">
        <h3 className="empty-title">{emptyTitle}</h3>
        <p>{emptyBody}</p>
      </div>
    );
  }
  return (
    <div className="grid collections-grid">
      {items.map(p => (
        <ProductCard key={p.id} p={p} isSaved={savedIds.includes(p.id)} showPrice={true} onOpen={(prod) => onOpenProduct(prod, items)} onSave={onSave} />
      ))}
    </div>
  );
}

function OwnedTabContent({ ownedItems, customOwnedItems, savedIds, onOpenProduct, onSave, onAddCustom, onRemoveCustom }) {
  const total = ownedItems.reduce((s, p) => s + (p.price || 0), 0)
              + customOwnedItems.reduce((s, p) => s + (Number(p.price) || 0), 0);

  return (
    <>
      <div className="owned-toolbar">
        <div className="owned-toolbar-l">
          <span className="owned-toolbar-h">{ownedItems.length + customOwnedItems.length} {(ownedItems.length + customOwnedItems.length) === 1 ? 'thing' : 'things'} you own</span>
          {total > 0 && <span className="owned-toolbar-total">approx ${total.toLocaleString()} value</span>}
        </div>
        <button className="btn" onClick={onAddCustom} style={{ width: 'auto', padding: '11px 18px' }}>
          <span>Add something we don't carry</span><span className="arrow">+</span>
        </button>
      </div>

      {ownedItems.length === 0 && customOwnedItems.length === 0 ? (
        <div className="empty collections-empty">
          <h3 className="empty-title">Nothing marked as owned yet</h3>
          <p>Open an essential and tap "We own this one" — or add something we don't carry yourself.</p>
        </div>
      ) : (
        <div className="grid collections-grid">
          {ownedItems.map(p => (
            <ProductCard key={p.id} p={p} isSaved={savedIds.includes(p.id)} showPrice={true} onOpen={(prod) => onOpenProduct(prod, ownedItems)} onSave={onSave} />
          ))}
          {customOwnedItems.map(item => (
            <CustomOwnedCard key={item.id} item={item} onRemove={() => onRemoveCustom(item.id)} />
          ))}
        </div>
      )}
    </>
  );
}

function CustomOwnedCard({ item, onRemove }) {
  const initials = (item.name || '?').slice(0, 1).toUpperCase();
  const palette = [
    ['#e0a94c','#cf5d4a'],['#3f6b54','#6280a3'],
    ['#cf5d4a','#3f6b54'],['#6280a3','#e0a94c'],
  ];
  const idx = (item.id || '').length % palette.length;
  const [c1, c2] = palette[idx];
  const stop = (e) => e.stopPropagation();
  return (
    <article className="card custom-owned-card">
      <div className="card-img custom-owned-img">
        {item.img ? (
          <img src={item.img} alt={item.name} loading="lazy" />
        ) : (
          <div
            className="custom-owned-placeholder"
            style={{ background: `linear-gradient(160deg, ${c1}, ${c2})` }}
            aria-hidden="true"
          >
            <span>{initials}</span>
          </div>
        )}
        <span className="card-tag custom-owned-tag">Added by you</span>
        <button
          className="custom-owned-remove"
          onClick={(e) => { stop(e); onRemove(); }}
          aria-label="Remove"
          title="Remove from your stuff"
        >
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
      </div>
      <div className="card-body">
        {item.brand && <div className="card-brand">{item.brand}</div>}
        <h3 className="card-name">{item.name}</h3>
        <div className="card-meta">
          {item.price ? <span className="card-price">${Number(item.price).toLocaleString()}</span> : <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>{item.notes ? '' : 'no price set'}</span>}
        </div>
        {item.notes && <p className="custom-owned-notes">{item.notes}</p>}
      </div>
    </article>
  );
}

function ListsTabContent({ userLists, productMap, onOpenList, onCreateList }) {
  if (!userLists.length) {
    return (
      <div className="empty collections-empty">
        <h3 className="empty-title">No lists yet</h3>
        <p>Create your first list — keep it private, share it with a partner, or open it up as a registry friends and family can buy from.</p>
        <div style={{ marginTop: 18, display: 'flex', justifyContent: 'center' }}>
          <button className="btn" onClick={onCreateList} style={{ width: 'auto', padding: '12px 22px' }}>
            <span>Start a new list</span><span className="arrow">+</span>
          </button>
        </div>
      </div>
    );
  }
  return (
    <>
      <div className="owned-toolbar">
        <div className="owned-toolbar-l">
          <span className="owned-toolbar-h">{userLists.length} {userLists.length === 1 ? 'list' : 'lists'}</span>
        </div>
        <button className="btn btn-ghost" onClick={onCreateList} style={{ width: 'auto', padding: '11px 18px' }}>
          <span>New list</span><span className="arrow">+</span>
        </button>
      </div>
      <div className="lists-grid">
        {userLists.map(l => (
          <ListCard key={l.id} list={l} productMap={productMap} onOpen={() => onOpenList(l)} />
        ))}
      </div>
    </>
  );
}

window.CollectionsPage = CollectionsPage;
