// Hoja «Elegir producto»: cambia, pone o quita el producto de súper de un
// ítem. Sustituye a la antigua hoja solo-Mercadona. Referencia visual:
// docs/design/multi-super/Vincular.dc.html. Elegir marca la opción (relleno
// de acento + háptica) y la hoja se cierra sola a los ~350 ms (al instante
// sin movimiento); tocar otra opción en esa ventana la cambia y reinicia el
// temporizador. «Quitar vínculo» cierra y ofrece deshacer.

// Abre la ficha oficial: navegador in-app de Capacitor si existe, si no una
// pestaña nueva. Solo recibe URLs ya validadas por `StoresCore.safeProductUrl`
// (https y dominio de la cadena): el vínculo puede llegar sincronizado.
function openStoreUrl(url) {
  const Browser = window.Capacitor?.Plugins?.Browser;
  if (Browser?.open) { Browser.open({ url }); return; }
  window.open(url, '_blank', 'noopener,noreferrer');
}

function StoreLinkSheet({ app, theme, itemId, onClose }) {
  const c = theme.c;
  const ts = app.t.stores;
  const item = (app.items || []).find(i => i.id === itemId);
  const [query, setQuery] = React.useState(item ? item.name : '');
  const [filter, setFilter] = React.useState('all');
  const state = useStoreSearch(query, app.stores);
  const closeTimer = React.useRef(null);
  React.useEffect(() => () => clearTimeout(closeTimer.current), []);

  // Igual que el resto de hojas con ítem: si desaparece, cerrar vía efecto.
  React.useEffect(() => { if (!item) onClose(); }, [item]);
  if (!item) return null;

  const current = StoresCore.itemStore(item);
  const currentKey = current ? StoresCore.productKey(current) : null;
  const chains = StoresCore.enabledChains(app.stores);
  const counts = {};
  if (state && state.chains) for (const id of Object.keys(state.chains)) counts[id] = state.chains[id].products.length;
  const results = StoresCore.sortByBulk(StoresCore.searchProducts(state, filter));
  const summary = state && !state.offline ? StoresCore.searchSummary(state) : null;
  const unavailable = state && state.chains ? Object.keys(state.chains).filter(id => state.chains[id].status === 'unavailable' || state.chains[id].status === 'error') : [];
  const motion = !!app.animations && !SLMotion.reducedMotion();
  const age = current ? StoresCore.staleDays(current, Date.now()) : null;
  const chainName = StoresCore.chainName;
  const webUrl = current ? StoresCore.safeProductUrl(current) : null;

  function pick(p) {
    if (StoresCore.productKey(p) !== currentKey) {
      app.updateItem(item.id, { store: p });
      SLMotion.haptic.selection();
    }
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(onClose, motion ? 350 : 0);
  }

  function unlink() {
    const prev = current;
    app.updateItem(item.id, { store: null });
    app.showUndo({ kind: 'unlink', item: { id: item.id, name: item.name }, prev, listId: app.currentListId, message: ts.unlinkedToast });
    SLMotion.haptic.light();
    onClose();
  }

  return (
    <Sheet theme={theme} mode={app.isDesktop ? 'dialog' : 'sheet'} open onClose={onClose} title={ts.chooseProduct}>
      <div data-testid="store-link-sheet">
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 22, fontWeight: 800, fontFamily: theme.fontDisplay, color: c.ink, letterSpacing: -0.3 }}>{item.name}</div>
          <div data-testid="store-link-current" aria-live="polite" style={{ marginTop: 4, minHeight: 20 }}>
            {current && (
              <div key={currentKey} className={motion ? 'sl-anim-fade' : ''}
                style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: c.inkSub, fontFamily: theme.fontBody, minWidth: 0 }}>
                <ChainBadge theme={theme} chain={current.chain} size={16} />
                <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {chainName(current.chain)} · {current.name}
                </span>
                <span style={{ fontWeight: 700, color: c.ink, fontFamily: theme.fontMono, flexShrink: 0 }}>{StoresCore.fmtEur(current.price)}</span>
                {webUrl && (
                  <button type="button" data-testid="store-link-web" onClick={() => openStoreUrl(webUrl)} style={{
                    flexShrink: 0, background: 'transparent', border: 'none', cursor: 'pointer',
                    color: c.ink, textDecoration: 'underline', fontWeight: 700, fontSize: 13,
                    fontFamily: theme.fontBody, minHeight: 44, padding: '16px 4px', margin: '-16px 0',
                  }}>{tpl(ts.viewOnWeb, { chain: chainName(current.chain) })}</button>
                )}
              </div>
            )}
            {age != null && (
              <div data-testid="store-link-age" style={{ fontSize: 12, color: c.inkSub, fontFamily: theme.fontBody, marginTop: 2 }}>
                {tpl(ts.priceAge, { days: age })}
              </div>
            )}
          </div>
        </div>

        <input data-testid="store-link-query" autoFocus={app.isDesktop} value={query} onChange={e => setQuery(e.target.value)}
          placeholder={ts.searchPlaceholder} aria-label={ts.searchPlaceholder}
          style={{
            width: '100%', height: 48, padding: '0 14px', fontSize: 15, fontFamily: theme.fontDisplay,
            border: `1.5px solid ${c.border}`, borderRadius: theme.radius.lg, outline: 'none',
            background: c.bg, color: c.ink, marginBottom: 10, boxSizing: 'border-box',
          }} />

        {chains.length > 1 && (
          <div style={{ marginBottom: 10 }}>
            <ChainChips theme={theme} chains={chains} counts={state && state.chains ? counts : null} value={filter} onChange={setFilter}
              allLabel={ts.all} label={ts.filterLabel} />
          </div>
        )}

        {unavailable.length > 0 && (
          <div role="status" style={{ fontSize: 12, color: c.inkSub, fontFamily: theme.fontBody, marginBottom: 8 }}>
            {tpl(ts.someUnavailable, { chains: unavailable.map(chainName).join(', ') })}
          </div>
        )}

        <div role="radiogroup" aria-label={ts.chooseProduct} className="sl-scroll"
          style={{ maxHeight: 360, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
          {results.map((p, i) => {
            const key = StoresCore.productKey(p);
            const active = key === currentKey;
            const d = active ? null : StoresCore.priceDiff(p, current);
            const right2 = active ? StoresCore.fmtBulk(p) : (d ? StoresCore.fmtDiff(d) : StoresCore.fmtBulk(p));
            const right2Color = !active && d && d.diff < 0 ? c.okInk : undefined;
            const sub = subOf(p, true, ts, app.stores.chains[p.chain]);
            return (
              <div key={key} style={{ flexShrink: 0, borderRadius: theme.radius.md, overflow: 'hidden', border: `1px solid ${active ? c.accent : c.border}` }}>
                <StoreProductRow theme={theme} product={p} testid="store-link-option" role="radio" checked={active} disabled={active}
                  sub={sub} right2={right2} right2Color={right2Color} active={active} index={i} animate={motion} onPick={pick}
                  ariaLabel={StoresCore.productLabel(p) + (d ? ', ' + StoresCore.fmtDiff(d) : '')} />
              </div>
            );
          })}
          {state && state.offline && <MessageRow theme={theme} testid="store-link-offline">{ts.offline}</MessageRow>}
          {summary && summary.settled && results.length === 0 && (
            <MessageRow theme={theme} testid="store-link-empty">
              {summary.allFailed ? ts.allFailed : tpl(ts.noResultsFor, { q: state.query })}
            </MessageRow>
          )}
          {summary && !summary.settled && results.length === 0 && (
            <div style={{ padding: '8px 4px' }}><StoreSpinner theme={theme} label={ts.loading} motion={motion} /></div>
          )}
        </div>

        {current && (
          <Btn theme={theme} variant="ghost" size="md" full icon="x" testid="store-link-unlink" onClick={unlink}>
            {ts.unlink}
          </Btn>
        )}
      </div>
    </Sheet>
  );
}

Object.assign(window, { StoreLinkSheet, openStoreUrl });
