/* Admin Tienda online — vitrina, fotos, landing y tienda completa */

const parseGalleryPathsRow = (row) => {
  const g = row?.gallery_paths;
  return Array.isArray(g) ? g.filter(p => typeof p === 'string' && p.trim()) : [];
};

const ProductStoreFormModal = ({ open, onClose, theme, product, onSaved }) => {
  const [form, setForm] = React.useState({
    active: false,
    show_on_landing: false,
    image_path: '',
    gallery_paths: [],
    cover_focus_x: 50,
    cover_focus_y: 50,
  });
  const [coverFile, setCoverFile] = React.useState(null);
  const [extraFiles, setExtraFiles] = React.useState([]);
  const [coverBlobUrl, setCoverBlobUrl] = React.useState(null);
  const [savedImageUrl, setSavedImageUrl] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState('');
  const fileInputRef = React.useRef(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const setFocus = (x, y) => setForm(f => ({ ...f, cover_focus_x: x, cover_focus_y: y }));

  React.useEffect(() => {
    if (!open || !product) return;
    setCoverFile(null);
    setExtraFiles([]);
    setErr('');
    const paths = parseGalleryPathsRow(product);
    setForm({
      active: product.active !== false,
      show_on_landing: product.show_on_landing === true,
      image_path: product.image_path || '',
      gallery_paths: paths,
      cover_focus_x: Number(product.cover_focus_x) || 50,
      cover_focus_y: Number(product.cover_focus_y) || 50,
    });
    setSavedImageUrl(product.image_path ? productImageUrl(product.image_path) : null);
    setCoverBlobUrl(null);
  }, [open, product?.id]);

  React.useEffect(() => {
    if (!coverFile) {
      setCoverBlobUrl(null);
      return undefined;
    }
    const url = URL.createObjectURL(coverFile);
    setCoverBlobUrl(url);
    return () => URL.revokeObjectURL(url);
  }, [coverFile]);

  const coverDisplayUrl = coverBlobUrl || savedImageUrl;

  const onPickCover = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
      alert('Selecciona una imagen (JPG, PNG o WebP).');
      return;
    }
    setCoverFile(file);
    e.target.value = '';
  };

  const save = async () => {
    if (!product?.id) return;
    setSaving(true);
    setErr('');
    try {
      let image_path = form.image_path || null;
      let gallery_paths = [...form.gallery_paths];

      if (coverFile) {
        image_path = await uploadProductImage(coverFile, product.id);
      }

      for (let i = 0; i < extraFiles.length; i++) {
        const path = await uploadProductImage(extraFiles[i], product.id);
        gallery_paths.push(path);
      }

      await updateProductStore({
        active: form.active,
        show_on_landing: form.show_on_landing,
        image_path,
        gallery_paths,
        cover_focus_x: form.cover_focus_x,
        cover_focus_y: form.cover_focus_y,
      }, product.id);

      setCoverFile(null);
      if (image_path) setSavedImageUrl(productImageUrl(image_path));
      notifyProductsChanged();
      onSaved?.();
      onClose();
    } catch (e) { setErr(e.message); }
    setSaving(false);
  };

  const removeGalleryPath = (path) => {
    setForm(f => ({ ...f, gallery_paths: f.gallery_paths.filter(p => p !== path) }));
  };

  if (!product) return null;

  const stockBy = parseStockBySize(product);
  const stockTotal = sumStockBySize(stockBy);

  return (
    <Modal open={open} onClose={onClose} theme={theme} title={`Tienda — ${product.name}`} width={720}>
      <div style={{ padding: '8px 24px 24px', display: 'grid', gap: 16, maxHeight: '78vh', overflowY: 'auto' }}>
        <p style={{ margin: 0, fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>
          Inventario: ${product.price} · {stockTotal} piezas. Edita stock en <strong>Inventario</strong>.
        </p>

        <div style={{
          padding: 14, borderRadius: 12, border: `1px solid ${theme.border}`, background: theme.bgInput,
          display: 'grid', gap: 12,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
            <div>
              <label style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>
                Foto principal del producto
              </label>
              <p style={{ margin: '6px 0 0', fontSize: 11, color: theme.textDim, fontFamily: 'Inter, sans-serif', maxWidth: 440 }}>
                Sube la imagen y <strong>arrastra</strong> en la vista previa para encuadrar. Pulsa <strong>Guardar vitrina</strong> para guardar la foto y el encuadre.
              </p>
            </div>
            <label style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 14px', borderRadius: 8,
              background: theme.primary, color: '#fff', fontSize: 12, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'Inter, sans-serif', flexShrink: 0,
            }}>
              <Icon name="upload" size={14} />
              {coverDisplayUrl ? 'Cambiar imagen' : 'Subir imagen'}
              <input ref={fileInputRef} type="file" accept="image/jpeg,image/png,image/webp" style={{ display: 'none' }} onChange={onPickCover} />
            </label>
          </div>

          {coverDisplayUrl ? (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
                <span style={{ fontSize: 11, color: theme.primary, fontWeight: 700, fontFamily: 'Inter, sans-serif' }}>
                  Arrastra la foto dentro del recuadro para ajustar el encuadre
                </span>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button type="button" onClick={() => setFocus(50, 50)}
                    style={{
                      fontSize: 11, padding: '4px 10px', borderRadius: 6, cursor: 'pointer',
                      border: `1px solid ${theme.border}`, background: theme.bg, color: theme.textDim,
                      fontFamily: 'Inter, sans-serif',
                    }}>
                    Centrar
                  </button>
                  {coverFile && (
                    <button type="button" onClick={() => setCoverFile(null)}
                      style={{
                        fontSize: 11, padding: '4px 10px', borderRadius: 6, cursor: 'pointer',
                        border: `1px solid ${theme.border}`, background: theme.bg, color: theme.danger,
                        fontFamily: 'Inter, sans-serif',
                      }}>
                      Descartar nueva
                    </button>
                  )}
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16, alignItems: 'start' }}>
                <div>
                  <div style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', marginBottom: 8, fontFamily: 'Inter, sans-serif' }}>
                    Preview — Landing
                  </div>
                  <Card theme={theme} style={{ padding: 0, overflow: 'hidden', maxWidth: 200 }}>
                    <LandingFocusPhotoFrame
                      theme={theme}
                      imageUrl={coverDisplayUrl}
                      focusX={form.cover_focus_x}
                      focusY={form.cover_focus_y}
                      onFocusChange={setFocus}
                      aspectRatio="4/3"
                      maxWidth={200}
                      badge={stockTotal > 0 ? (
                        <div style={{
                          position: 'absolute', top: 8, right: 8, padding: '3px 8px', borderRadius: 999,
                          background: 'rgba(0,0,0,0.55)', fontSize: 9, fontWeight: 700, color: '#fff',
                          fontFamily: 'Inter, sans-serif', pointerEvents: 'none',
                        }}>{stockTotal < 10 ? `Quedan ${stockTotal}` : 'En stock'}</div>
                      ) : null}
                    />
                    <div style={{ padding: '10px 12px' }}>
                      <div style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>{product.category}</div>
                      <div style={{ fontWeight: 600, fontSize: 13, color: theme.text, fontFamily: 'Inter, sans-serif', marginTop: 2 }}>{product.name}</div>
                      <div style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 22, color: theme.primary, marginTop: 4 }}>${product.price}</div>
                    </div>
                  </Card>
                </div>

                <div>
                  <div style={{ fontSize: 10, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', marginBottom: 8, fontFamily: 'Inter, sans-serif' }}>
                    Preview — Tienda completa
                  </div>
                  <Card theme={theme} style={{ padding: 0, overflow: 'hidden', maxWidth: 200 }}>
                    <LandingFocusPhotoFrame
                      theme={theme}
                      imageUrl={coverDisplayUrl}
                      focusX={form.cover_focus_x}
                      focusY={form.cover_focus_y}
                      onFocusChange={setFocus}
                      aspectRatio="1/1"
                      maxWidth={200}
                    />
                    <div style={{ padding: 10, fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif' }}>
                      Mismo encuadre en tienda.html y al ordenar.
                    </div>
                  </Card>
                </div>
              </div>
            </>
          ) : (
            <div style={{
              padding: 32, textAlign: 'center', borderRadius: 10, border: `2px dashed ${theme.border}`,
              color: theme.textMute, fontFamily: 'Inter, sans-serif', fontSize: 13,
            }}>
              <Icon name="image" size={36} color={theme.textMute} />
              <p style={{ margin: '12px 0 0' }}>Sube una imagen para ver la vista previa y ajustar el encuadre con arrastre.</p>
            </div>
          )}
        </div>

        <div style={{ display: 'grid', gap: 10 }}>
          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>
            <input type="checkbox" checked={form.active} onChange={e => set('active', e.target.checked)} style={{ marginTop: 3 }} />
            <span>
              <strong style={{ fontSize: 13 }}>Visible en tienda completa</strong>
              <span style={{ display: 'block', fontSize: 11, color: theme.textDim, marginTop: 2 }}>Aparece en tienda.html para ordenar.</span>
            </span>
          </label>
          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', cursor: 'pointer', fontFamily: 'Inter, sans-serif' }}>
            <input type="checkbox" checked={form.show_on_landing} onChange={e => set('show_on_landing', e.target.checked)} style={{ marginTop: 3 }} />
            <span>
              <strong style={{ fontSize: 13 }}>Mostrar en landing</strong>
              <span style={{ display: 'block', fontSize: 11, color: theme.textDim, marginTop: 2 }}>Tarjeta compacta en la página principal (sección Tienda).</span>
            </span>
          </label>
        </div>

        <div>
          <label style={{ fontSize: 11, color: theme.textMute, fontWeight: 700, textTransform: 'uppercase', fontFamily: 'Inter, sans-serif' }}>Más fotos</label>
          <input type="file" accept="image/*" multiple onChange={e => setExtraFiles(Array.from(e.target.files || []))}
            style={{ marginTop: 8, fontSize: 12, display: 'block', fontFamily: 'Inter, sans-serif' }} />
          {extraFiles.length > 0 && (
            <div style={{ fontSize: 11, color: theme.textDim, marginTop: 4, fontFamily: 'Inter, sans-serif' }}>
              {extraFiles.length} nueva(s) por subir al guardar
            </div>
          )}
          {form.gallery_paths.length > 0 && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
              {form.gallery_paths.map(path => (
                <div key={path} style={{ position: 'relative', width: 72, height: 72, borderRadius: 8, overflow: 'hidden', border: `1px solid ${theme.border}` }}>
                  <img src={productImageUrl(path)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  <button type="button" onClick={() => removeGalleryPath(path)}
                    style={{
                      position: 'absolute', top: 2, right: 2, width: 20, height: 20, borderRadius: 4,
                      border: 'none', background: theme.danger, color: '#fff', cursor: 'pointer', fontSize: 12, lineHeight: 1,
                    }}>×</button>
                </div>
              ))}
            </div>
          )}
        </div>

        {err && <div style={{ color: theme.danger, fontSize: 13, fontFamily: 'Inter, sans-serif' }}>{err}</div>}
      </div>
      <div style={{ padding: '16px 24px', borderTop: `1px solid ${theme.border}`, display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <Btn theme={theme} kind="ghost" onClick={onClose}>Cancelar</Btn>
        <Btn theme={theme} icon="check" onClick={save} disabled={saving}>{saving ? 'Guardando…' : 'Guardar vitrina'}</Btn>
      </div>
    </Modal>
  );
};

const ProductTiendaAdminModule = ({ theme }) => {
  const { rows, loading, error, needsAuth, reload } = useAdminList(() => fetchAllProducts(), []);
  const [editProduct, setEditProduct] = React.useState(null);

  return (
    <AdminEntityShell theme={theme} title="TIENDA ONLINE" sub="Todos los productos del inventario: fotos, encuadre y visibilidad." icon="cart">
      {needsAuth ? <AuthRequired theme={theme} onRetry={reload} /> : loading ? <LoadingBlock theme={theme} /> : error ? (
        <EmptyState theme={theme} title="Error" message={error} />
      ) : rows.length === 0 ? (
        <EmptyState theme={theme} title="Sin productos" message="Agrega productos primero en Inventario." icon="cart" />
      ) : (
        <Card theme={theme} style={{ padding: 0 }}>
          {rows.map(r => {
            const thumb = r.image_path ? productImageUrl(r.image_path) : null;
            const flags = [
              r.show_on_landing ? 'Landing' : null,
              r.active !== false ? 'Tienda completa' : null,
            ].filter(Boolean).join(' · ') || 'Sin publicar';
            return (
              <div key={r.id} style={{ padding: 14, borderBottom: `1px solid ${theme.border}`, display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 8, overflow: 'hidden', flexShrink: 0,
                  border: `1px solid ${theme.border}`, background: theme.bgInput,
                  display: 'grid', placeItems: 'center',
                }}>
                  {thumb ? <img src={thumb} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <Icon name="cart" size={20} color={theme.textMute} />}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700 }}>{r.name}</div>
                  <div style={{ fontSize: 12, color: theme.textDim }}>${r.price} · {flags}</div>
                </div>
                <Btn theme={theme} kind="soft" size="sm" icon="edit" onClick={() => setEditProduct(r)}>Configurar</Btn>
              </div>
            );
          })}
        </Card>
      )}
      <ProductStoreFormModal
        open={!!editProduct}
        onClose={() => setEditProduct(null)}
        theme={theme}
        product={editProduct}
        onSaved={reload}
      />
    </AdminEntityShell>
  );
};

Object.assign(window, { ProductTiendaAdminModule, ProductStoreFormModal });
