// "Identify by photo" — opens a modal that takes a photo, sends it to
// /api/identify-product (Claude Vision), shows the identification result
// with a catalog-match suggestion, and either accepts or hands off the
// identification into the Quick Add form for refinement.

const { useState: _ye, useEffect: _yu, useRef: _yr } = React;

function IdentifyByPhotoModal({ open, onClose, onIdentified }) {
  const [stage, setStage] = _ye('upload'); // 'upload' | 'thinking' | 'result' | 'error'
  const [imgPreview, setImgPreview] = _ye('');     // base64 data URL for preview
  const [imgUploaded, setImgUploaded] = _ye('');   // public Supabase URL (or fallback base64)
  const [result, setResult] = _ye(null);
  const [err, setErr] = _ye('');
  const fileRef = _yr(null);
  const cancelledRef = _yr(false);

  _yu(() => {
    if (open) {
      setStage('upload'); setImgPreview(''); setImgUploaded(''); setResult(null); setErr('');
      cancelledRef.current = false;
    } else {
      cancelledRef.current = true;
    }
  }, [open]);

  if (!open) return null;

  const handleFile = async (file) => {
    if (!file) return;
    setErr('');
    setStage('thinking');
    try {
      // 1. Show preview immediately
      const localDataUrl = await compressImageToDataUrl(file, { maxDim: 1024, quality: 0.85 });
      if (cancelledRef.current) return;
      setImgPreview(localDataUrl);

      // 2. Upload (or fall back to base64) so we have a stable URL for catalog ingest
      const uploaded = await uploadOrEncodeImage(file);
      if (cancelledRef.current) return;
      setImgUploaded(uploaded.url);

      // 3. Send the image to Claude
      const resp = await fetch('/api/identify-product', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ image: localDataUrl }),
      });
      const json = await resp.json();
      if (cancelledRef.current) return;
      if (!resp.ok || !json.ok) {
        setErr(json.error || 'Identification failed');
        setStage('error');
        return;
      }
      const id = json.identification || {};
      if (id.error) {
        if (id.error === 'not_a_product') {
          setErr(`That doesn't look like a baby/kid product. ${id.what_you_see ? '— "' + id.what_you_see + '"' : ''} Try a different photo?`);
        } else {
          setErr(id.reason || 'The image is too unclear to identify confidently.');
        }
        setStage('error');
        return;
      }
      setResult(id);
      setStage('result');
    } catch (e) {
      setErr(e.message || 'Could not process the image');
      setStage('error');
    }
  };

  // Catalog match — fuzzy search by brand + name tokens
  const catalogMatch = (() => {
    if (!result) return null;
    const all = window.PRODUCTS || [];
    if (!all.length) return null;
    const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\s+/g, ' ').trim();
    const target = norm(`${result.brand || ''} ${result.name || ''}`);
    if (!target) return null;
    const tokens = new Set(target.split(' ').filter(t => t.length > 2));
    if (tokens.size < 2) return null;
    let best = null, score = 0;
    all.forEach(p => {
      const cand = norm(`${p.brand || ''} ${p.name || ''}`);
      const ct = new Set(cand.split(' ').filter(t => t.length > 2));
      let overlap = 0;
      tokens.forEach(t => { if (ct.has(t)) overlap++; });
      const s = (overlap / Math.min(tokens.size, ct.size))
        + (result.brand && p.brand && norm(result.brand) === norm(p.brand) ? 0.2 : 0);
      if (s > score) { score = s; best = p; }
    });
    return score >= 0.5 ? { product: best, score } : null;
  })();

  const handleAccept = () => {
    if (!result || !onIdentified) return;
    onIdentified({
      identification: result,
      imageUrl: imgUploaded,
      catalogMatch: catalogMatch && catalogMatch.product,
    });
  };

  return (
    <>
      <div className="auth-scrim" onClick={onClose} />
      <div className="identify-modal" role="dialog" aria-modal="true" aria-label="Identify by photo">
        <button type="button" className="thankyou-close" onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 16, right: 16 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6 L18 18 M18 6 L6 18"/></svg>
        </button>

        {stage === 'upload' && (
          <div className="identify-upload">
            <div className="identify-eyebrow">Add by photo</div>
            <h2 className="identify-h">
              Snap it — we'll <em><Whimsy text="figure it out" /></em>
            </h2>
            <p className="identify-sub">
              Point your camera at a baby thing, or pick a photo from your library.
              We'll identify the brand, model, and category and prefill a new entry for your list.
            </p>
            <button type="button" className="identify-camera" onClick={() => fileRef.current && fileRef.current.click()}>
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M3 7 h4 l2 -2 h6 l2 2 h4 v12 H3z"/>
                <circle cx="12" cy="13" r="4"/>
              </svg>
              <span className="identify-camera-h">Take or pick a photo</span>
              <span className="identify-camera-hint">Best results: clean background, product front-facing, brand label visible if possible</span>
            </button>
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              capture="environment"
              style={{ display: 'none' }}
              onChange={(e) => { const f = e.target.files && e.target.files[0]; if (f) handleFile(f); e.target.value = ''; }}
            />
          </div>
        )}

        {stage === 'thinking' && (
          <div className="identify-thinking">
            {imgPreview && <img src={imgPreview} alt="" className="identify-thinking-img" />}
            <div className="identify-thinking-spinner" aria-hidden="true">
              <span>✦</span><span>✧</span><span>✦</span>
            </div>
            <p className="identify-thinking-label">Squinting at pixels…</p>
            <p className="identify-thinking-sub">Asking Claude to identify the brand and model. Usually takes 2-4 seconds.</p>
          </div>
        )}

        {stage === 'result' && result && (
          <div className="identify-result">
            <div className="identify-result-head">
              {imgPreview && <img src={imgPreview} alt="" className="identify-result-img" />}
              <div className="identify-result-headbody">
                <div className="identify-eyebrow">{Math.round((result.confidence || 0) * 100)}% confident</div>
                <h2 className="identify-result-h">
                  {result.brand ? <><span className="identify-result-brand">{result.brand}</span><br /></> : null}
                  {result.name || 'Identified product'}
                </h2>
                {result.estimated_age_range && (
                  <div className="identify-result-age">Age: {result.estimated_age_range}</div>
                )}
              </div>
            </div>

            {result.description && (
              <p className="identify-result-desc">{result.description}</p>
            )}

            {catalogMatch && (
              <div className="quick-add-match" style={{ marginTop: 14 }}>
                <div className="quick-add-match-thumb">
                  {catalogMatch.product.img && <img src={catalogMatch.product.img} alt="" />}
                </div>
                <div className="quick-add-match-body">
                  <div className="quick-add-match-eyebrow">Looks like one we already track</div>
                  <div className="quick-add-match-name">{catalogMatch.product.brand} · {catalogMatch.product.name}</div>
                  <div className="quick-add-match-sub">Using the catalog version gets you hi-res images, retailer links, and full specs.</div>
                </div>
              </div>
            )}

            {result.materials && (
              <div className="identify-result-fact">
                <span className="identify-result-fact-lbl">Materials</span>
                <span>{result.materials}</span>
              </div>
            )}
            {result.category && (
              <div className="identify-result-fact">
                <span className="identify-result-fact-lbl">Category</span>
                <span>{result.category}</span>
              </div>
            )}

            <div className="identify-actions">
              <button type="button" className="btn btn-ghost" onClick={() => { setStage('upload'); setResult(null); }} style={{ width: 'auto', padding: '10px 14px' }}>
                <span>Try a different photo</span>
              </button>
              <button type="button" className="btn" onClick={handleAccept} style={{ width: 'auto', padding: '10px 18px' }}>
                <span className="btn-row">
                  {catalogMatch ? 'Use this catalog match' : 'Add to my list →'}
                </span>
                <span className="arrow">→</span>
              </button>
            </div>
          </div>
        )}

        {stage === 'error' && (
          <div className="identify-error">
            <div className="identify-error-icon">😅</div>
            <h3 className="identify-error-h">Couldn't identify it</h3>
            <p className="identify-error-sub">{err}</p>
            <div className="identify-actions">
              <button type="button" className="btn btn-ghost" onClick={onClose} style={{ width: 'auto', padding: '10px 14px' }}>
                <span>Close</span>
              </button>
              <button type="button" className="btn" onClick={() => { setStage('upload'); setErr(''); }} style={{ width: 'auto', padding: '10px 18px' }}>
                <span className="btn-row">Try another photo</span>
                <span className="arrow">→</span>
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

window.IdentifyByPhotoModal = IdentifyByPhotoModal;
