// Per-stage essentials checklist + per-item detail page.
// State shape: picks[itemId] = { pickedProductId, owned, inRegistry }

function EssentialsPage({ stage, stageData, picks, onChangeStage, onOpenItem, onShare, onToggleOwned, onToggleRegistry, onRemoveItem, onRestoreItem, onAddInSection }) {
  const stageKeys = window.ESSENTIAL_STAGE_KEYS || Object.keys(window.ESSENTIALS_BY_STAGE);
  const data = stageData || window.ESSENTIALS_BY_STAGE[stage] || window.ESSENTIALS_BY_STAGE.pre;

  const productMap = useMemo(() => {
    const m = {};
    (window.PRODUCTS || []).forEach(p => { m[p.id] = p; });
    return m;
  }, []);

  const allItems = useMemo(() => data.sections.flatMap(s => s.items), [data]);
  const removedItems = data.removedItems || [];

  const stats = useMemo(() => {
    let pickedCount = 0, ownedCount = 0, registryCount = 0, total = 0;
    allItems.forEach(it => {
      const p = picks[it.id];
      if (!p) return;
      if (p.pickedProductId && !p.owned) {
        pickedCount += 1;
        const prod = productMap[p.pickedProductId];
        if (prod) total += prod.price;
      }
      if (p.owned) ownedCount += 1;
      if (p.inRegistry) registryCount += 1;
    });
    return { pickedCount, ownedCount, registryCount, total, totalItems: allItems.length };
  }, [picks, allItems, productMap]);

  const completion = stats.totalItems > 0
    ? Math.round(((stats.pickedCount + stats.ownedCount) / stats.totalItems) * 100)
    : 0;

  return (
    <div className="page essentials-page">
      <div className="essentials-pagehead">
        <div className="essentials-pagehead-left">
          <div className="page-eyebrow">Essentials · {data.label}</div>
          <h1 className="page-title">Everything they need <em>(and nothing they don't)</em></h1>
          <p className="page-sub">{data.sub}</p>
        </div>
        <aside className="essentials-tally">
          <div className="essentials-tally-row">
            <div className="essentials-tally-stat">
              <span className="num">{stats.pickedCount + stats.ownedCount}<em>/{stats.totalItems}</em></span>
              <span className="lbl">Sorted</span>
            </div>
            <div className="essentials-tally-stat">
              <span className="num">${stats.total.toLocaleString()}</span>
              <span className="lbl">Still to spend</span>
            </div>
            <div className="essentials-tally-stat">
              <span className="num">{stats.ownedCount}</span>
              <span className="lbl">You own</span>
            </div>
          </div>
          <div className="essentials-tally-bar" aria-label={`${completion}% complete`}>
            <div className="essentials-tally-bar-fill" style={{ width: `${completion}%` }} />
          </div>
          <div className="essentials-tally-actions">
            <button className="btn" onClick={onShare} style={{ width: '100%', padding: '11px 16px' }}>
              <span>Share with partner</span><span className="arrow">→</span>
            </button>
          </div>
        </aside>
      </div>

      <div className="essentials-stagebar" role="tablist" aria-label="Stage">
        {stageKeys.map(key => {
          const s = window.ESSENTIALS_BY_STAGE[key];
          if (!s) return null;
          return (
            <button
              key={key}
              role="tab"
              aria-selected={stage === key}
              className={`essentials-stagepill${stage === key ? ' is-current' : ''}`}
              onClick={() => onChangeStage(key)}
            >
              <span className="essentials-stagepill-h">{s.short}</span>
              <span className="essentials-stagepill-sub">{s.label}</span>
            </button>
          );
        })}
      </div>

      {data.sections.map(section => (
        <section key={section.id} className="essentials-section">
          <div className="essentials-section-head">
            <h2 className="essentials-section-title">{section.label}</h2>
            <span className="essentials-section-count">{section.items.length} {section.items.length === 1 ? 'thing' : 'things'}</span>
          </div>
          <div className="essentials-grid">
            {section.items.map(item => (
              <EssentialItemCard
                key={item.id}
                item={item}
                pick={picks[item.id]}
                productMap={productMap}
                onOpen={() => onOpenItem(item.id)}
                onToggleOwned={() => onToggleOwned(item.id)}
                onToggleRegistry={() => onToggleRegistry(item.id)}
                onRemove={() => onRemoveItem(item.id, !!item.custom)}
              />
            ))}
            <button
              className="essentials-addcard"
              onClick={() => onAddInSection(section.id)}
              aria-label={`Add an essential to ${section.label}`}
            >
              <span className="essentials-addcard-plus">+</span>
              <span className="essentials-addcard-lbl">Add an essential</span>
              <span className="essentials-addcard-sub">Something missing? Add it.</span>
            </button>
          </div>
        </section>
      ))}

      {removedItems.length > 0 && (
        <section className="essentials-hidden">
          <details>
            <summary>
              <span className="essentials-hidden-h">{removedItems.length} hidden</span>
              <span className="essentials-hidden-sub">Items you marked as not for you. Click to show / restore.</span>
            </summary>
            <ul className="essentials-hidden-list">
              {removedItems.map(item => (
                <li key={item.id}>
                  <span className="essentials-hidden-name">{item.label}</span>
                  <button className="essentials-hidden-restore" onClick={() => onRestoreItem(item.id)}>
                    <span>Restore</span><span className="arrow">↺</span>
                  </button>
                </li>
              ))}
            </ul>
          </details>
        </section>
      )}
    </div>
  );
}

function EssentialItemCard({ item, pick, productMap, onOpen, onToggleOwned, onToggleRegistry, onRemove }) {
  const ownedProduct = pick && pick.pickedProductId && pick.owned ? productMap[pick.pickedProductId] : null;
  const pickedProduct = pick && pick.pickedProductId && !pick.owned ? productMap[pick.pickedProductId] : null;
  const isOwnedGeneric = pick && pick.owned && !pick.pickedProductId;
  const isRegistry = pick && pick.inRegistry;
  const stop = (e) => e.stopPropagation();

  const heroImg = ownedProduct || pickedProduct;
  const isCustom = !!item.custom;

  return (
    <article
      className={`essentials-item${heroImg ? ' is-picked' : ''}${pick && pick.owned ? ' is-owned' : ''}${isCustom ? ' is-custom' : ''}`}
      onClick={onOpen}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(); } }}
    >
      <button
        className="essentials-item-remove"
        onClick={(e) => { stop(e); onRemove(); }}
        title={isCustom ? 'Delete this' : 'Hide this from my list'}
        aria-label="Remove from list"
      >
        <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 className="essentials-item-thumbs" aria-hidden="true">
        {heroImg ? (
          <img src={heroImg.img} alt="" loading="lazy" />
        ) : (item.productIds && item.productIds.length > 0) ? (
          item.productIds.slice(0, 4).map(pid => {
            const p = productMap[pid];
            return p ? <img key={pid} src={p.img} alt="" loading="lazy" /> : null;
          })
        ) : (
          <div className="essentials-item-thumb-placeholder">
            <span>{(item.label || '·').charAt(0)}</span>
          </div>
        )}
      </div>
      <div className="essentials-item-body">
        <div className="essentials-item-h">
          <h3>{item.label}</h3>
          {item.necessity === 'must' && <span className="essentials-badge essentials-badge-must">Must-have</span>}
          {item.necessity === 'nice' && <span className="essentials-badge essentials-badge-nice">Nice-to-have</span>}
        </div>
        {item.blurb && <p className="essentials-item-blurb">{item.blurb}</p>}
        {isCustom && <p className="essentials-item-blurb"><em>Added by you.</em></p>}
        <div className="essentials-item-status">
          {ownedProduct ? (
            <span className="essentials-status owned">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
              You own: {ownedProduct.brand}
            </span>
          ) : isOwnedGeneric ? (
            <span className="essentials-status owned">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
              You already own one
            </span>
          ) : pickedProduct ? (
            <span className="essentials-status picked">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
              {pickedProduct.brand} · ${pickedProduct.price.toLocaleString()}
            </span>
          ) : (
            <span className="essentials-status open">
              {(item.productIds || []).length > 0
                ? <>{(item.productIds || []).length} {(item.productIds || []).length === 1 ? 'option' : 'options'} <span className="arrow">→</span></>
                : <>Pick options <span className="arrow">→</span></>
              }
            </span>
          )}
          {isRegistry && (
            <span className="essentials-chip">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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>
              On registry
            </span>
          )}
        </div>
        <div className="essentials-item-quick" onClick={stop}>
          <button
            className={`essentials-quick${pick && pick.owned ? ' is-on' : ''}`}
            onClick={(e) => {
              stop(e);
              // If this item has product options, send the user to the detail
              // page so they can pick exactly which one they own. Custom items
              // with no productIds keep the simple boolean toggle.
              if ((item.productIds || []).length > 0) {
                onOpen();
              } else {
                onToggleOwned();
              }
            }}
            aria-pressed={!!(pick && pick.owned)}
          >
            {pick && pick.owned
              ? (ownedProduct ? '✓ Own ' + ownedProduct.brand : '✓ Owned')
              : ((item.productIds || []).length > 0 ? 'I own one →' : 'I own one')}
          </button>
          <button
            className={`essentials-quick${isRegistry ? ' is-on' : ''}`}
            onClick={(e) => { stop(e); onToggleRegistry(); }}
            aria-pressed={!!isRegistry}
          >
            {isRegistry ? '✓ On registry' : 'Add to registry'}
          </button>
        </div>
      </div>
    </article>
  );
}

function EssentialItemDetailPage({ stage, stageData, itemId, picks, savedIds, onBack, onPick, onMarkOwned, onToggleOwned, onToggleRegistry, onNavToItem, onOpenProduct, onSave }) {
  const data = stageData || window.ESSENTIALS_BY_STAGE[stage] || window.ESSENTIALS_BY_STAGE.pre;
  const allItems = data.sections.flatMap(s => s.items);
  const idx = allItems.findIndex(i => i.id === itemId);
  const item = allItems[idx];
  if (!item) {
    return (
      <div className="page">
        <button className="btn btn-ghost" onClick={onBack} style={{ width: 'auto', padding: '8px 14px' }}>
          <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span><span>Back to checklist</span>
        </button>
        <div className="empty">
          <h3 className="empty-title">Item not found</h3>
        </div>
      </div>
    );
  }

  const productMap = useMemo(() => {
    const m = {};
    (window.PRODUCTS || []).forEach(p => { m[p.id] = p; });
    return m;
  }, []);
  const products = (item.productIds || []).map(id => productMap[id]).filter(Boolean);

  const pick = picks[item.id] || {};
  const prev = idx > 0 ? allItems[idx - 1] : null;
  const next = idx < allItems.length - 1 ? allItems[idx + 1] : null;

  // For arrow-key nav we stay *within the current section* — jumping from
  // "Sleep" into "Going places" by tapping → felt jarring. Bottom nav buttons
  // still cross sections so the user can keep moving forward through the list.
  const currentSection = data.sections.find(s => s.items.some(i => i.id === itemId));
  const sectionItems = currentSection ? currentSection.items : allItems;
  const sIdx = sectionItems.findIndex(i => i.id === itemId);
  const sectionPrev = sIdx > 0 ? sectionItems[sIdx - 1] : null;
  const sectionNext = sIdx >= 0 && sIdx < sectionItems.length - 1 ? sectionItems[sIdx + 1] : null;

  // keyboard nav between items in the current section. Skip if a product
  // detail panel is open on top — its own arrow handler should win.
  useEffect(() => {
    const onKey = (e) => {
      if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
      if (document.querySelector('.detail.is-open')) return;
      if (e.key === 'ArrowLeft' && sectionPrev) { e.preventDefault(); onNavToItem(sectionPrev.id); }
      if (e.key === 'ArrowRight' && sectionNext) { e.preventDefault(); onNavToItem(sectionNext.id); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [sectionPrev, sectionNext, onNavToItem]);

  const ownedProduct = pick.pickedProductId && pick.owned ? productMap[pick.pickedProductId] : null;
  const pickedProduct = pick.pickedProductId && !pick.owned ? productMap[pick.pickedProductId] : null;

  return (
    <div className="page essential-item-page">
      <div className="essential-item-topnav">
        <button className="btn btn-ghost" onClick={onBack} style={{ width: 'auto', padding: '8px 14px' }}>
          <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span><span>All essentials</span>
        </button>
        <div className="essential-item-stepnav">
          <button
            className={`essential-step${prev ? '' : ' is-disabled'}`}
            onClick={() => prev && onNavToItem(prev.id)}
            disabled={!prev}
            aria-label={prev ? `Previous: ${prev.label}` : 'No previous item'}
          >
            <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span>
            <span className="essential-step-lbl">{prev ? prev.label : 'Start of list'}</span>
          </button>
          <span className="essential-step-count">{idx + 1} of {allItems.length}</span>
          <button
            className={`essential-step${next ? '' : ' is-disabled'}`}
            onClick={() => next && onNavToItem(next.id)}
            disabled={!next}
            aria-label={next ? `Next: ${next.label}` : 'End of list'}
          >
            <span className="essential-step-lbl">{next ? next.label : 'End of list'}</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </div>

      <div className="essential-item-hero">
        <div className="essential-item-hero-text">
          <div className="page-eyebrow">{data.label} · Item {idx + 1}</div>
          <h1 className="essential-item-title">{item.label}</h1>
          {item.blurb && <p className="essential-item-blurb">{item.blurb}</p>}
          {item.custom && !item.blurb && <p className="essential-item-blurb"><em>You added this. There aren't preset options yet — browse the catalog or pick something from Discover.</em></p>}
          <div className="essential-item-toggles">
            <button
              className={`essential-toggle${pick.owned && !pick.pickedProductId ? ' is-on' : ''}`}
              onClick={() => onToggleOwned(item.id)}
              aria-pressed={!!(pick.owned && !pick.pickedProductId)}
            >
              <span className="check"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5L20 7"/></svg></span>
              <span>{pick.owned && !pick.pickedProductId ? 'Marked as owned' : 'I own one (no specific brand)'}</span>
            </button>
            <button
              className={`essential-toggle${pick.inRegistry ? ' is-on' : ''}`}
              onClick={() => onToggleRegistry(item.id)}
              aria-pressed={!!pick.inRegistry}
            >
              <span className="check"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5L20 7"/></svg></span>
              <span>On the registry</span>
            </button>
            {item.necessity === 'must' && <span className="essentials-badge essentials-badge-must" style={{ alignSelf: 'center' }}>Must-have</span>}
            {item.necessity === 'nice' && <span className="essentials-badge essentials-badge-nice" style={{ alignSelf: 'center' }}>Nice-to-have</span>}
          </div>
        </div>
        {(ownedProduct || pickedProduct) && (
          <div className={`essential-item-pick${ownedProduct ? ' is-owned' : ''}`}>
            <div className="essential-item-pick-eyebrow">{ownedProduct ? "What you've got" : 'Your pick'}</div>
            <img src={(ownedProduct || pickedProduct).img} alt="" />
            <div className="essential-item-pick-name">{(ownedProduct || pickedProduct).name}</div>
            <div className="essential-item-pick-meta">{(ownedProduct || pickedProduct).brand} · ${(ownedProduct || pickedProduct).price.toLocaleString()}</div>
          </div>
        )}
      </div>

      <div className="essential-options">
        <div className="essential-options-head">
          <h2 className="essential-options-title">{products.length} {products.length === 1 ? 'option' : 'options'}</h2>
          <span className="essential-options-meta">Pick the one you'd like — or mark one you already own.</span>
        </div>
        {products.length === 0 ? (
          <div className="empty">
            <h3 className="empty-title">No options yet</h3>
            <p>Browse Discover to find a product, then come back to mark it as your pick.</p>
          </div>
        ) : (
          <div className="grid">
            {products.map(p => {
              const isPicked = pick.pickedProductId === p.id && !pick.owned;
              const isOwnedHere = pick.pickedProductId === p.id && pick.owned;
              return (
                <div key={p.id} className={`essential-option${isPicked ? ' is-picked' : ''}${isOwnedHere ? ' is-owned' : ''}`}>
                  <ProductCard p={p} isSaved={savedIds.includes(p.id)} showPrice={true} onOpen={(prod) => onOpenProduct(prod, products)} onSave={onSave} />
                  <div className="essential-pick-row">
                    <button
                      className={`essential-pick-btn${isPicked ? ' is-picked' : ''}`}
                      onClick={() => onPick(item.id, p.id)}
                    >
                      {isPicked ? (
                        <span><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6"><path d="M5 12l5 5L20 7"/></svg> Picked</span>
                      ) : (
                        <><span>Pick this one</span><span className="arrow">→</span></>
                      )}
                    </button>
                    <button
                      className={`essential-own-btn${isOwnedHere ? ' is-owned' : ''}`}
                      onClick={() => onMarkOwned(item.id, p.id)}
                      title="We already own this exact one"
                    >
                      {isOwnedHere ? (
                        <span><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6"><path d="M5 12l5 5L20 7"/></svg> Got it</span>
                      ) : (
                        <span>We own this one</span>
                      )}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      <div className="essential-item-bottomnav">
        <button
          className="btn btn-ghost"
          disabled={!prev}
          onClick={() => prev && onNavToItem(prev.id)}
          style={{ width: 'auto', padding: '14px 20px', opacity: prev ? 1 : 0.4 }}
        >
          <span className="arrow" style={{ transform: 'rotate(180deg)' }}>→</span>
          <span>{prev ? prev.label : 'Start of list'}</span>
        </button>
        <button
          className="btn"
          disabled={!next}
          onClick={() => next ? onNavToItem(next.id) : onBack()}
          style={{ width: 'auto', padding: '14px 22px', opacity: next ? 1 : 0.6 }}
        >
          <span>{next ? `Next: ${next.label}` : 'Back to checklist'}</span>
          <span className="arrow">→</span>
        </button>
      </div>
    </div>
  );
}

window.EssentialsPage = EssentialsPage;
window.EssentialItemDetailPage = EssentialItemDetailPage;
