// AddAlternativeModal — focused mini-add for appending a candidate to an
// existing list item. Paste a URL, we fetch product data via og-fetch and
// optionally match it to the catalog, then on confirm we hand the candidate
// back via onAdd({ productId? , custom? , label? }).
//
// Deliberately smaller than the AddByLinkModal — no status picker, no list
// selector, no registry toggle. The alternative inherits all that from the
// item it's being added to.

// Alias React hooks. Babel scripts share global scope but other files in
// this project explicitly destructure here for clarity.
const { useState: _alts, useEffect: _alte, useRef: _altr } = React;

function AddAlternativeModal({ target, currentItemName, onClose, onAdd }) {
  const [url, setUrl] = _alts('');
  const [busy, setBusy] = _alts(false);
  const [err, setErr] = _alts('');
  const [fetched, setFetched] = _alts(null);
  const inputRef = _altr(null);

  _alte(() => {
    if (inputRef.current) inputRef.current.focus();
  }, []);

  const handleFetch = async () => {
    const u = url.trim();
    if (!u) return;
    setErr('');
    setBusy(true);
    try {
      const resp = await fetch(`/api/og-fetch?url=${encodeURIComponent(u)}`);
      const json = await resp.json();
      if (!resp.ok || !json || !json.ok || !json.data) {
        setErr(json && json.error ? json.error : "Couldn't read that page");
        setBusy(false);
        return;
      }
      const data = json.data;
      // Decode HTML entities in the title (matches AddByLink behavior).
      const decode = (s) => s ? s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#039;/g, "'") : '';
      data.title = decode(data.title);
      // We used to fuzzy-match the og-fetched title into the catalog so a
      // pasted URL could "upgrade" to a real catalog product. In practice
      // that mis-matched on brand alone (e.g. a Cybex pram URL would land
      // a Cybex car seat) and surprised users. Trust the URL: always
      // surface the real og-fetched payload as the candidate.
      setFetched({ ...data, catalogMatch: null });
    } catch (e) {
      setErr(String(e.message || e));
    }
    setBusy(false);
  };

  const handleAdd = () => {
    if (!fetched) return;
    // Prefer the catalog match if we found one — gets us hi-res images,
    // retailer links, real product ID. Otherwise pass a custom candidate.
    if (fetched.catalogMatch) {
      onAdd({
        productId: fetched.catalogMatch.id,
        label: fetched.catalogMatch.name,
      });
    } else {
      onAdd({
        custom: {
          name: fetched.title,
          brand: fetched.brand,
          image: fetched.image,
          price: fetched.price,
          currency: fetched.currency || 'AUD',
          source_url: fetched.sourceUrl,
          description: fetched.description,
        },
        label: fetched.title,
      });
    }
  };

  return (
    <>
      <div className="add-modal-scrim is-open" onClick={onClose} />
      <div className="add-modal add-modal--alt is-open" role="dialog" aria-modal="true" aria-label="Add an alternative">
        <button type="button" className="add-modal-close" aria-label="Close" onClick={onClose}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
        <div className="add-modal-body">
          <div className="addalt-intro">
            <div className="addalt-eyebrow">Add an alternative</div>
            <h2 className="addalt-h">
              Compare against <em>{currentItemName || 'this item'}</em>
            </h2>
            <p className="addalt-sub">
              Paste a product link from anywhere on the web. We'll fetch the details
              and add it as an option you can switch between later.
            </p>
          </div>

          {!fetched ? (
            <form
              className="addalt-form"
              onSubmit={(e) => { e.preventDefault(); handleFetch(); }}
            >
              <input
                ref={inputRef}
                type="url"
                className="quick-add-input"
                placeholder="https://www.lovevery.com/products/…"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                inputMode="url"
                autoComplete="off"
              />
              <button
                type="submit"
                className="btn"
                disabled={!url.trim() || busy}
                style={{ width: '100%', padding: '12px 16px' }}
              >
                <span>{busy ? 'Reading…' : 'Read this link'}</span><span className="arrow">→</span>
              </button>
              {err && <div className="quick-add-err" style={{ marginTop: 8 }}>{err}</div>}
            </form>
          ) : (
            <div className="addalt-preview">
              <div className="addalt-preview-thumb">
                {fetched.image
                  ? <img src={fetched.image} alt="" />
                  : <span className="addalt-preview-imgempty">—</span>}
              </div>
              <div className="addalt-preview-body">
                {fetched.catalogMatch && (
                  <div className="addalt-preview-catalog">In our catalog · {fetched.catalogMatch.brand}</div>
                )}
                {fetched.brand && <div className="addalt-preview-brand">{fetched.brand}</div>}
                <div className="addalt-preview-name">{fetched.title}</div>
                {fetched.price && (
                  <div className="addalt-preview-price">
                    {fetched.currency === 'AUD' ? 'A$' : '$'}{Number(fetched.price).toLocaleString()}
                  </div>
                )}
                <div className="addalt-actions">
                  <button type="button" className="btn btn-ghost" onClick={() => setFetched(null)} style={{ width: 'auto', padding: '10px 14px' }}>
                    <span>Try another</span>
                  </button>
                  <button type="button" className="btn" onClick={handleAdd} style={{ flex: 1, padding: '10px 16px' }}>
                    <span>Add as alternative</span><span className="arrow">→</span>
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

window.AddAlternativeModal = AddAlternativeModal;
