// Photo search modal — drag/drop or camera capture, simulated visual match against catalog

function PhotoSearchModal({ open, onClose, onResult }) {
  const [stage, setStage] = React.useState('idle'); // idle | processing | results
  const [filePreview, setFilePreview] = React.useState(null);
  const [results, setResults] = React.useState([]);
  const [hot, setHot] = React.useState(false);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) {
      // reset on close after fade
      const t = setTimeout(() => { setStage('idle'); setFilePreview(null); setResults([]); }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      setFilePreview(e.target.result);
      runMatch();
    };
    reader.readAsDataURL(file);
  };

  const runMatch = () => {
    setStage('processing');
    // Simulate 3-stage pipeline: upload → vision → catalog match
    setTimeout(() => {
      // Pick 3 plausible matches with descending confidence
      const shuffled = [...PRODUCTS].sort(() => Math.random() - 0.5).slice(0, 3);
      const matched = shuffled.map((p, i) => ({
        product: p,
        confidence: [97, 84, 71][i],
      }));
      setResults(matched);
      setStage('results');
    }, 1800);
  };

  const onDrop = (e) => {
    e.preventDefault();
    setHot(false);
    const file = e.dataTransfer.files?.[0];
    if (file && file.type.startsWith('image/')) handleFile(file);
  };

  return (
    <div
      className={`photo-modal ${open ? 'photo-modal--open' : ''}`}
      onClick={onClose}
      aria-hidden={!open}
    >
      <div className="photo-modal__dialog" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="photo-modal-title">
        <header className="photo-modal__head">
          <div>
            <div className="photo-modal__title" id="photo-modal-title">Foto ile arama</div>
            <div className="photo-modal__sub">Parça fotoğrafı yükleyin — kataloğumuzdan eşleşeni bulalım</div>
          </div>
          <button className="compare-drawer__close" onClick={onClose} aria-label="Kapat">
            <Icon name="close" size={18} stroke={2}/>
          </button>
        </header>

        <div className="photo-modal__body">
          {stage === 'idle' && (
            <>
              <div
                className={`dropzone ${hot ? 'dropzone--hot' : ''}`}
                onDragOver={(e) => { e.preventDefault(); setHot(true); }}
                onDragLeave={() => setHot(false)}
                onDrop={onDrop}
                onClick={() => inputRef.current?.click()}
              >
                <div className="dropzone__icon">
                  <Icon name="image" size={28} stroke={1.6}/>
                </div>
                <h3>Fotoğrafı buraya sürükleyin</h3>
                <p>PNG, JPG veya WEBP — en fazla 8 MB</p>
              </div>

              <div className="dropzone__or">veya</div>

              <div className="photo-actions">
                <button className="btn btn--ghost btn--block" onClick={() => inputRef.current?.click()}>
                  <Icon name="upload" size={14} stroke={2}/> Cihazdan yükle
                </button>
                <button
                  className="btn btn--ghost btn--block"
                  onClick={() => {
                    // Simulate camera — in real app would request getUserMedia
                    handleFile({ name: 'camera-capture.jpg', type: 'image/jpeg' });
                    setFilePreview(null);
                  }}
                >
                  <Icon name="camera" size={14} stroke={2}/> Kamera kullan
                </button>
              </div>

              <input
                ref={inputRef}
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                onChange={(e) => handleFile(e.target.files?.[0])}
              />

              <p style={{ marginTop: 16, fontSize: 11, color: 'var(--km-ink-400)', textAlign: 'center', lineHeight: 1.5 }}>
                Fotoğrafınız <strong>cihazınızda</strong> kalır, sadece embedding (yüz tanıma içermeyen vektör) sunucumuza gönderilir. 24 saatte silinir.
              </p>
            </>
          )}

          {stage === 'processing' && (
            <>
              <div style={{
                aspectRatio: '4 / 3',
                background: filePreview ? `center / contain no-repeat url(${filePreview}), var(--km-paper-2)` : 'var(--km-paper-2)',
                backgroundImage: filePreview ? `url(${filePreview})` : `repeating-linear-gradient(135deg, rgba(15,27,45,0.04) 0 1px, transparent 1px 10px)`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                borderRadius: 12,
                border: '1px solid var(--km-line)',
                position: 'relative',
                overflow: 'hidden',
              }}>
                {!filePreview && (
                  <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--km-ink-400)', fontSize: 12, fontFamily: 'var(--font-mono)' }}>
                    camera capture
                  </div>
                )}
                <div style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, transparent 40%, rgba(15,27,45,0.4) 100%)',
                  pointerEvents: 'none',
                }}/>
                <div style={{
                  position: 'absolute', bottom: 12, left: 12,
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  background: 'rgba(255,255,255,0.96)', padding: '6px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600,
                }}>
                  <span className="photo-spinner"/>
                  Görüntü analiz ediliyor...
                </div>
              </div>

              <div className="photo-progress">
                <ProgressStep done label="Görsel yüklendi" delay={0}/>
                <ProgressStep done label="Vektör (embedding) çıkarıldı" delay={500}/>
                <ProgressStep active label="Katalog ile eşleştiriliyor..." delay={1200}/>
              </div>
            </>
          )}

          {stage === 'results' && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, fontSize: 13, color: 'var(--km-ink-600)' }}>
                <Icon name="check-circle" size={16} stroke={2} style={{ color: 'var(--km-good)' }}/>
                <strong>{results.length} olası eşleşme</strong> bulundu — güven sırasına göre
              </div>

              <div className="photo-results">
                {results.map(({ product, confidence }, i) => (
                  <a
                    key={product.shortSlug}
                    href={urlForProduct(product)}
                    className="photo-result"
                    onClick={onResult}
                  >
                    <div style={{
                      width: 56, aspectRatio: 1, borderRadius: 6,
                      background: 'repeating-linear-gradient(135deg, rgba(15,27,45,0.04) 0 1px, transparent 1px 8px), var(--km-paper-2)',
                      border: '1px solid var(--km-line)',
                      flexShrink: 0,
                    }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--km-ink-500)', fontWeight: 600 }}>{product.brand}</div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--km-ink-900)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{product.h1}</div>
                      <div style={{ fontSize: 12, color: 'var(--km-ink-500)' }} className="tabular">
                        {formatPrice(productLowest(product))} · {product.offers.length} satıcıdan
                      </div>
                    </div>
                    <span className="photo-result__match tabular">%{confidence}</span>
                  </a>
                ))}
              </div>

              <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
                <button className="btn btn--ghost btn--block" onClick={() => { setStage('idle'); setFilePreview(null); }}>
                  Başka fotoğraf dene
                </button>
              </div>
              <p style={{ marginTop: 12, fontSize: 11, color: 'var(--km-ink-400)', textAlign: 'center' }}>
                Doğru sonuç yok mu? <a href="#/" style={{ color: 'var(--km-deep)' }}>Aramayı manuel başlatın</a>
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function ProgressStep({ active, done, label, delay }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setShown(true), delay);
    return () => clearTimeout(t);
  }, [delay]);
  if (!shown) return null;
  return (
    <div className={`photo-progress__step ${active ? 'photo-progress__step--active' : ''} ${done ? 'photo-progress__step--done' : ''}`}>
      {done ? <Icon name="check" size={14} stroke={2.4}/> : <span className="photo-spinner"/>}
      <span>{label}</span>
    </div>
  );
}

Object.assign(window, { PhotoSearchModal });
