// Camera capture + analysis modal
const CaptureScreen = ({ onClose, currentStore }) => {
  const [phase, setPhase] = useState('camera'); // camera | analyzing | success | error
  const [errorMsg, setErrorMsg] = useState('');
  const [flash, setFlash] = useState(false);
  const [flashOn, setFlashOn] = useState(false);

  const takePhoto = () => {
    setFlash(true);
    setTimeout(() => setFlash(false), 200);
    setTimeout(() => setPhase('analyzing'), 250);
    // Randomize success/error for demo
    setTimeout(() => {
      const ok = Math.random() > 0.35;
      if (ok) setPhase('success');
      else { setErrorMsg('No detectamos el precio en la foto. Asegúrate de que la etiqueta esté visible y enfocada.'); setPhase('error'); }
    }, 3200);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'black', zIndex: 200, display: 'flex', flexDirection: 'column' }}>
      <StatusBar light/>
      {/* Viewfinder */}
      <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
        {/* Faux camera scene */}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, #2a3140 0%, #4a5160 100%)' }}/>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.5, background: 'radial-gradient(ellipse at center, rgba(255,255,255,0.18) 0%, transparent 70%)' }}/>
        {/* Faux product shelf */}
        <div style={{ position: 'absolute', left: '8%', right: '8%', top: '20%', bottom: '30%', display: 'flex', gap: 12 }}>
          {['#d4385e', '#1b9a5f', '#ff6b3d', '#ffc845'].map((c, i) => (
            <div key={i} style={{ flex: 1, background: `linear-gradient(180deg, ${c}aa, ${c}55)`, borderRadius: 8, position: 'relative' }}>
              <div style={{ position: 'absolute', bottom: 16, left: 4, right: 4, height: 24, background: 'rgba(255,255,255,0.85)', borderRadius: 3, padding: '3px 4px', fontSize: 10, fontWeight: 800, color: '#1a2330', textAlign: 'center', fontFamily: 'JetBrains Mono, monospace' }}>$3.20</div>
            </div>
          ))}
        </div>

        {/* Focus frame */}
        <div style={{ position: 'absolute', left: '12%', right: '12%', top: '22%', bottom: '32%', border: '2px solid rgba(255,255,255,0.85)', borderRadius: 14 }}>
          {/* corners */}
          {[[0,0],[1,0],[0,1],[1,1]].map(([x,y], i) => (
            <div key={i} style={{ position: 'absolute', width: 22, height: 22, [x?'right':'left']: -2, [y?'bottom':'top']: -2, borderTop: y?'none':'4px solid var(--c-primary)', borderBottom: y?'4px solid var(--c-primary)':'none', borderLeft: x?'none':'4px solid var(--c-primary)', borderRight: x?'4px solid var(--c-primary)':'none', borderRadius: y && x ? '0 0 6px 0' : y ? '0 0 0 6px' : x ? '0 6px 0 0' : '6px 0 0 0' }}/>
          ))}
        </div>

        {/* Top overlay */}
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button onClick={onClose} style={{ width: 40, height: 40, borderRadius: 20, background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)', border: 'none', color: 'white', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
            <Icon name="close" size={20} color="white"/>
          </button>
          <div style={{ background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)', borderRadius: 20, padding: '7px 12px', display: 'flex', alignItems: 'center', gap: 7, color: 'white' }}>
            <StoreDot color={currentStore.color} short={currentStore.short} size={22}/>
            <span style={{ fontSize: 13, fontWeight: 700 }}>{currentStore.name}</span>
          </div>
          <button onClick={() => setFlashOn(!flashOn)} style={{ width: 40, height: 40, borderRadius: 20, background: flashOn ? 'var(--c-yellow)' : 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)', border: 'none', color: flashOn ? '#5e4500' : 'white', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
            <Icon name="flash" size={20} color={flashOn ? '#5e4500' : 'white'}/>
          </button>
        </div>

        {/* Helper text */}
        <div style={{ position: 'absolute', left: 22, right: 22, top: 64, textAlign: 'center', color: 'white' }}>
          <div style={{ display: 'inline-block', padding: '8px 14px', background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)', borderRadius: 16, fontSize: 13, fontWeight: 600 }}>
            <Icon name="sparkle" size={14} color="#ffc845"/> &nbsp;Enmarca el producto <b>y la etiqueta de precio</b>
          </div>
        </div>

        {/* flash */}
        {flash && <div style={{ position: 'absolute', inset: 0, background: 'white', animation: 'fade-in .15s ease' }}/>}
      </div>

      {/* Bottom controls */}
      <div style={{ background: 'black', padding: '20px 24px 30px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
        <div style={{ width: 50, height: 50, borderRadius: 12, background: '#1f2436', display: 'grid', placeItems: 'center', color: '#7a8194' }}>
          <Icon name="package" size={22} color="#7a8194"/>
        </div>
        <button onClick={takePhoto} style={{ width: 78, height: 78, borderRadius: 50, background: 'transparent', border: '4px solid white', display: 'grid', placeItems: 'center', cursor: 'pointer', padding: 0 }}>
          <div style={{ width: 60, height: 60, borderRadius: 30, background: 'white' }}/>
        </button>
        <button style={{ width: 50, height: 50, borderRadius: 25, background: '#1f2436', border: 'none', display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'white' }}>
          <Icon name="flip" size={22} color="white"/>
        </button>
      </div>

      {phase === 'analyzing' && <AnalysisModal/>}
      {phase === 'success' && <SuccessModal onDone={onClose}/>}
      {phase === 'error' && <ErrorModal msg={errorMsg} onRetry={() => setPhase('camera')} onClose={onClose}/>}
    </div>
  );
};

const AnalysisModal = () => {
  const [progress, setProgress] = useState(0);
  const steps = ['Detectando producto…', 'Leyendo etiqueta de precio…', 'Validando información…'];
  useEffect(() => {
    let p = 0;
    const t = setInterval(() => { p += 3; setProgress(Math.min(p, 96)); }, 60);
    return () => clearInterval(t);
  }, []);
  const stepIdx = progress < 33 ? 0 : progress < 66 ? 1 : 2;
  return (
    <div className="modal-center">
      <div className="modal-card" style={{ paddingBottom: 28 }}>
        {/* Scanner visual */}
        <div style={{ position: 'relative', width: 150, height: 150, margin: '0 auto 22px' }}>
          <svg width="150" height="150" viewBox="0 0 150 150" style={{ transform: 'rotate(-90deg)' }}>
            <circle cx="75" cy="75" r="62" stroke="var(--c-line-2)" strokeWidth="8" fill="none"/>
            <circle cx="75" cy="75" r="62" stroke="var(--c-primary)" strokeWidth="8" fill="none" strokeLinecap="round" strokeDasharray="389.5" strokeDashoffset={389.5 - (389.5 * progress / 100)} style={{ transition: 'stroke-dashoffset .15s linear' }}/>
          </svg>
          <div style={{ position: 'absolute', inset: 16, borderRadius: '50%', background: 'var(--c-primary-soft)', display: 'grid', placeItems: 'center' }}>
            <div style={{ position: 'relative', width: 70, height: 70 }}>
              <Icon name="package" size={56} color="var(--c-primary-deep)"/>
              {/* scan line */}
              <div style={{ position: 'absolute', left: -6, right: -6, top: '50%', height: 2, background: 'linear-gradient(90deg, transparent, var(--c-primary), transparent)', boxShadow: '0 0 12px var(--c-primary)', animation: 'drift 1.4s ease-in-out infinite' }}/>
            </div>
          </div>
          <div style={{ position: 'absolute', inset: 0, fontSize: 13, fontWeight: 900, display: 'grid', placeItems: 'center', color: 'var(--c-primary-deep)', transform: 'translateY(54px)' }}>{progress}%</div>
        </div>
        <h2 style={{ fontSize: 20 }}>Analizando tu foto</h2>
        <p className="muted small" style={{ marginTop: 8 }}>Nuestra IA está leyendo el producto y la etiqueta.</p>
        <div className="stack stack-2" style={{ marginTop: 22, textAlign: 'left' }}>
          {steps.map((s, i) => (
            <div key={i} className="row gap-3" style={{ padding: '10px 12px', borderRadius: 12, background: i === stepIdx ? 'var(--c-primary-soft)' : 'transparent', opacity: i > stepIdx ? 0.4 : 1, transition: 'all .2s' }}>
              <div style={{ width: 22, height: 22, borderRadius: 11, background: i < stepIdx ? 'var(--c-primary)' : i === stepIdx ? 'white' : 'var(--c-line)', display: 'grid', placeItems: 'center', border: i === stepIdx ? '2px solid var(--c-primary)' : 'none', flexShrink: 0 }}>
                {i < stepIdx ? <Icon name="check" size={12} color="white" stroke={3}/> : i === stepIdx ? <div style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--c-primary)', animation: 'pulse-ring 1.2s ease-out infinite' }}/> : null}
              </div>
              <div className="small" style={{ fontWeight: 700, color: i === stepIdx ? 'var(--c-primary-deep)' : 'var(--c-ink-2)' }}>{s}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const SuccessModal = ({ onDone }) => (
  <div className="modal-center">
    <Confetti/>
    <div className="modal-card" style={{ position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 50% 30%, var(--c-primary-soft) 0%, transparent 60%)' }}/>
      <div style={{ position: 'relative' }}>
        <div style={{ width: 110, height: 110, margin: '0 auto 18px', position: 'relative' }}>
          {/* Pulse rings */}
          <div style={{ position: 'absolute', inset: 0, border: '3px solid var(--c-primary)', borderRadius: '50%', animation: 'pulse-ring 2s ease-out infinite' }}/>
          <div style={{ position: 'absolute', inset: 0, border: '3px solid var(--c-primary)', borderRadius: '50%', animation: 'pulse-ring 2s ease-out infinite .6s' }}/>
          <svg width="110" height="110" viewBox="0 0 110 110">
            <circle cx="55" cy="55" r="48" fill="var(--c-primary)" style={{ filter: 'drop-shadow(0 10px 24px rgba(27,154,95,0.45))' }}/>
            <path d="M32 56 L48 72 L80 38" stroke="white" strokeWidth="7" fill="none" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="80" strokeDashoffset="80" style={{ animation: 'check-draw .6s .15s ease-out forwards' }}/>
          </svg>
        </div>
        <h2 style={{ fontSize: 24 }}>¡Precio capturado!</h2>
        <p className="muted small" style={{ marginTop: 8, padding: '0 8px' }}>Validamos el producto y el precio. La comunidad PrecioVivo te lo agradece.</p>

        <div className="card pop-in" style={{ marginTop: 20, padding: 14, background: 'var(--c-primary-soft)', border: '1px solid #b9e7cf', animationDelay: '.4s' }}>
          <div className="row gap-3" style={{ alignItems: 'center' }}>
            <ProductImg kind="green" size="sm"/>
            <div style={{ flex: 1, textAlign: 'left' }}>
              <div style={{ fontWeight: 800, fontSize: 14 }}>Aguacate Hass</div>
              <div className="tiny" style={{ color: 'var(--c-primary-deep)', fontWeight: 700, marginTop: 2 }}>VerdoMarket · $1.80</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="row gap-2" style={{ background: 'white', padding: '4px 10px', borderRadius: 12, color: 'var(--c-primary-deep)' }}>
                <Icon name="plus" size={14} color="var(--c-primary-deep)"/>
                <span style={{ fontWeight: 900, fontSize: 14 }}>50 pts</span>
              </div>
            </div>
          </div>
        </div>

        <button onClick={onDone} className="btn btn-primary btn-block" style={{ marginTop: 18 }}>
          <Icon name="check" size={18} color="white" stroke={2.6}/> Listo
        </button>
        <button className="btn btn-ghost btn-block" style={{ marginTop: 8, background: 'transparent', border: 'none', height: 40 }}>
          <Icon name="camera" size={16}/> Capturar otro producto
        </button>
      </div>
    </div>
  </div>
);

const ErrorModal = ({ msg, onRetry, onClose }) => (
  <div className="modal-center">
    <div className="modal-card">
      <div style={{ width: 92, height: 92, margin: '0 auto 18px', position: 'relative' }}>
        <svg width="92" height="92" viewBox="0 0 92 92">
          <circle cx="46" cy="46" r="40" fill="var(--c-berry-soft)" stroke="var(--c-berry)" strokeWidth="2"/>
          <path d="M46 28 L46 50" stroke="var(--c-berry)" strokeWidth="6" strokeLinecap="round"/>
          <circle cx="46" cy="62" r="3.5" fill="var(--c-berry)"/>
        </svg>
      </div>
      <h2 style={{ fontSize: 22 }}>Falta el precio</h2>
      <p className="muted small" style={{ marginTop: 8 }}>{msg}</p>
      <div className="card" style={{ marginTop: 18, padding: 12, background: '#fff8eb', border: '1px solid #f3dca8', textAlign: 'left' }}>
        <div className="row gap-2" style={{ alignItems: 'flex-start' }}>
          <Icon name="sparkle" size={16} color="#a07900"/>
          <div className="tiny" style={{ color: '#7a5b00', lineHeight: 1.45, fontWeight: 600 }}>
            <b>Consejo:</b> mantén la etiqueta dentro del marco, evita reflejos y procura buena luz.
          </div>
        </div>
      </div>
      <div className="stack stack-2" style={{ marginTop: 18 }}>
        <button onClick={onRetry} className="btn btn-primary btn-block">
          <Icon name="camera" size={18} color="white"/> Volver a intentar
        </button>
        <button onClick={onClose} className="btn btn-ghost btn-block">Cancelar</button>
      </div>
    </div>
  </div>
);

Object.assign(window, { CaptureScreen });
